/**
 * 
 */
package com.roc.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.roc.bean.JsonBean;
import com.roc.bean.MerinfoChangeBean;
import com.roc.bean.MerinfoDetail;
import com.roc.bean.TermBean;
import com.roc.dao.DaoException;
import com.roc.dao.IAgentDao;
import com.roc.dao.IBaseDao;
import com.roc.dao.IMerchantDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.dao.ISysLogDao;
import com.roc.dao.IorgDao;
import com.roc.dao.agent.IAgentInfoDao;
import com.roc.dao.impl.ITerminalDaoImpl;
import com.roc.dao.profit.IProfitDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Esmidinfo;
import com.roc.pojo.EsmidinfoMerinfo;
import com.roc.pojo.EsmidinfoTmp;
import com.roc.pojo.Estidinfo;
import com.roc.pojo.MccCode;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.MerinfoChange;
import com.roc.pojo.MerinfoStatusChange;
import com.roc.pojo.MerinfoStop;
import com.roc.pojo.MessageSend;
import com.roc.pojo.Module;
import com.roc.pojo.OperRole;
import com.roc.pojo.OperatorAuth;
import com.roc.pojo.OperatorReceive;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.PayBank;
import com.roc.pojo.SysLog;
import com.roc.pojo.TChangeReceive;
import com.roc.pojo.TReceive;
import com.roc.pojo.TblDictionaryLayerItem;
import com.roc.pojo.TblEditMchtBankAccount;
import com.roc.pojo.TblEditMchtBizDeal;
import com.roc.pojo.TblEditMchtBizFee;
import com.roc.pojo.TblEditMchtExtendInfo;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblEditMchtPicture;
import com.roc.pojo.TblEditTermInf;
import com.roc.pojo.TblEditTermInfId;
import com.roc.pojo.TblEditTermRiskCfg;
import com.roc.pojo.TblEditTermRiskCfgId;
import com.roc.pojo.TblMchtBankAccount;
import com.roc.pojo.TblMchtBizDeal;
import com.roc.pojo.TblMchtBizFee;
import com.roc.pojo.TblMchtBizFeeHis;
import com.roc.pojo.TblMchtBusiness;
import com.roc.pojo.TblMchtExtendInfo;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblMchtPicture;
import com.roc.pojo.TblOrgMain;
import com.roc.pojo.TblTermInf;
import com.roc.pojo.TblTermInfId;
import com.roc.pojo.TblTermRiskCfg;
import com.roc.pojo.TblTermRiskCfgId;
import com.roc.pojo.TermInfo;
import com.roc.pojo.TermInfoTmp;
import com.roc.pojo.YjPosAgent;
import com.roc.pojo.YjPosInfo;
import com.roc.pojo.susesMerinfo;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateTime;
import com.roc.util.DateUtil;
import com.roc.util.HttpUtil;
import com.roc.util.MD5Utils;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.MerinfoChangeReturninfo;
import com.roc.util.constant.MerinfoReturninfo;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SysLogType;
import com.roc.util.constant.Terminal;
import com.roc.util.constant.TerminalFlag;
import com.roc.web.action.merinfo.MerinfoAlloatSearchCondtion;
import com.ws.client.FourElementValidateUtils;


/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Company: </p>
* @author 
* @date 2016年11月21日上午11:45:18
*/
@Service
@Transactional(rollbackFor = { ServiceException.class })
public class MerchantServiceImpl implements IMerchantServices {

	static Logger logger = LogManager.getLogger(MerchantServiceImpl.class);

	@Autowired
	private IMerchantDao merchantDao;

	@Autowired
	private IBaseDao baseDao;
	
	@Autowired
	private IProfitDao profitDao;
	
	@Autowired
	private IPageDao  pageDao;
	
	@Autowired
	private ITerminalDaoImpl terminalDao;

	@Autowired
	private ISysLogDao sysLogDao;

	@Autowired
	ISQLBaseDao sqlBaseDao;

	@Autowired
	IorgDao orgDao;
	
	@Autowired
	private IAgentDao  agentDao;

	@Autowired
	IAgentService agentService;
	
	@Autowired
	private IAgentInfoDao agentInfoDao;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Double mchtFeeDtPercent;
	private Double mchtFeeDtPctMax;
	@Autowired
	IPowerInfoService powerInfoService;


	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.service.IMerchantServices#login(com.roc.pojo.Merchant)
	 */

	
	public Operators login(Operators loginMerchant) throws ServiceException {
		checkMerchantNo(loginMerchant);
		String merchantNo = loginMerchant.getAccountNo();
		Operators result = null;
		try {
			result = merchantDao.findUniqueMerchantByNo(merchantNo);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new ServiceException("获取用户信息失败");
		}

		return result;
	}

	@Override
	public Operators getOpertorsByAccountNo(String accountNo)
			throws ServiceException {
		Operators operators = null;
		try {
			operators=profitDao.getDlpOpertorsByAccountNo(accountNo);
		}catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询发展人不唯一！");
			}
		return operators;
	}
	public void loginAfter(Operators loginOperators) throws ServiceException {

		String accountNo = loginOperators.getAccountNo();
		Operators result = null;
		try {
			checkMerchantNo(loginOperators);
			List<Object> params = new ArrayList<Object>();
			params.add(Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01));
			params.add(loginOperators.getLoginIp());
			params.add(loginOperators.getPwdErrTimes());
			params.add(accountNo);
			sqlBaseDao
					.deleteBySql(
							"update t_operators t set t.last_login_time=?,t.login_ip=?,t.pwd_err_times=?,t.dt_lastmod=sysdate where t.account_no=? ",
							params);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new ServiceException("更新用户信息失败");
		}

	}

	private void checkMerchantNo(Operators loginMerchant)
			throws ServiceException {
		if (loginMerchant == null
				|| StringUtils.isBlank(loginMerchant.getAccountNo())) {
			throw new ServiceException("输入的用户账号为空");
		}
	}

	public Operators modifyPwd(Operators merchant) throws ServiceException {

		Operators result = null;
		try {
			result = merchantDao.loadMerchantById(merchant.getId());
			if (result == null) {
				throw new ServiceException("用户不存在");
			}
			result.setPwd(merchant.getPwd());
			result.setLastLoginTime(merchant.getLastLoginTime());
			result.setLoginIp(merchant.getLoginIp());
			result.setDtLostmod(new Date());
			result.setPwdErrTimes(0);
			result.setUpdatePWD(DateFormatUtils.format(new Date(), "yyyyMMdd"));
			String updatePWD = DateFormatUtils.format(new Date(), "yyyyMMdd");
			result.setUpdatePWD(updatePWD);
			
			merchantDao.editSave(result);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new ServiceException("用户信息修改失败");
		}
		return result;
	}

	public Operators findMerchantByNo(String accountNo) throws ServiceException {
		if (StringUtils.isBlank(accountNo)) {
			throw new ServiceException("账号为空");
		}
		Operators result = null;

		try {
			result = merchantDao.findUniqueMerchantByNo(accountNo);

		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询代理商信息失败");
		}
		return result;
	}

	@Override
	public String addMerchant(Operators oper, Operators operators)
			throws ServiceException {
	//	boolean result = true;
		String pwd = Utils.getRandomString();
		try {
			
			oper.setPwd(MD5Utils.MD5Encode(pwd));
			Date date = new Date();
			oper.setValidStartDate(DateUtil.initStartDate(date));
			oper.setValidEndDate(DateUtil.initEndDate());
			oper.setStatus(OperatorsStatus.OK.getCode());

			merchantDao.editSave(oper);
			
			
			StringBuffer sb = new StringBuffer();
			sb.append("您已开通付临门收单运营平台，您的账号：").append(oper.getAccountNo()).append("，您的密码是：").append(pwd).append("，系统的链接地址为：https://shoudan.freemypay.com:18081/fmposm/login.jsp。");
			logger.info("保存发送短信内容："+sb.toString());
			MessageSend ms = new MessageSend();
			ms.setPhoneNumber(oper.getMobile());
			ms.setMesContent(sb.toString());
			ms.setSendFlag("0");
			ms.setDtCreate(new Date());
			ms.setTimes(0);
			merchantDao.editSave(ms);

			merchantDao.addSyslog(SysLogType.OPERATORS_ADD.getCode(),
					SysLogType.OPERATORS_ADD.getName(), operators.getAccountNo(), operators.getAccountNo()
							+ "添加操作员【" + oper.getAccountNo() + "】");
			if(StringUtils.isNotEmpty(oper.getAreaIdRole())&&oper.getAreaIdRole().equals("-1")){
				List<TblOrgMain> list = agentService.queryOrgMainListByOrg();
				for(TblOrgMain operatorsR:list){
					OperRole operRole = new OperRole();
					operRole.setAreaCode(operatorsR.getAreaId());
					operRole.setInsCode(operatorsR.getSuperId());
					operRole.setAgentId(operatorsR.getOrg_code());
					operRole.setCreDate(DateTime.getNow("yyyyMMddHHmmss"));
					operRole.setStatus("00");
					operRole.setOperId(String.valueOf(oper.getId()));
					baseDao.editSave(operRole);
				}
			}else{
				if(oper.getOperRoleList()!=null&&oper.getOperRoleList().size()>0){
					List<OperRole> operRoles = new ArrayList<OperRole>();
					operRoles = oper.getOperRoleList();
					for(OperRole operRole:operRoles){
						operRole.setCreDate(DateTime.getNow("yyyyMMddHHmmss"));
						operRole.setStatus("0");
						operRole.setOperId(String.valueOf(oper.getId()));
						baseDao.editSave(operRole);
					}
				}
			}
			

		} catch (DaoException e) {
		//	result = false;
			logger.debug(e.getMessage());
			throw new ServiceException("操作员信息信息录入失败");

		}
		return pwd;
	}

	@Override
	public Operators loadMerchat(Long merchantId) throws ServiceException {
		if (merchantId == null || merchantId == 0) {
			throw new ServiceException("请选择一个代理商号后再分配PSAM卡");
		}
		Operators result = null;

		try {
			result = merchantDao.loadMerchantById(merchantId);

		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询代理商信息失败");
		}
		return result;
	}

	@Override
	public List<Operators> findSubMerchant(Long merchantId, String merType)
			throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		StringBuffer sb = new StringBuffer(" from Merchant t where 1=1 ");
		try {
			if (Constance.MERCHANT_TYPE_DAILI.equals(merType)
					|| Constance.MERCHANT_TYPE_SYSTEM.equals(merType)) {
				sb.append(" and t.merType='01' and t.superiorId=" + merchantId);
			} else if (Constance.MERCHANT_TYPE_CAIWU.equals(merType)
					|| Constance.MERCHANT_TYPE_STORE.equals(merType)
					|| Constance.MERCHANT_TYPE_MARKET.equals(merType)) {
				sb.append(" and t.merType='01' and t.superiorId=1 ");
			} else {
				sb.append(" and t.merType='01' and t.recommenderId="
						+ merchantId);
			}
			sb.append(" order by t.realName ");
			List<Object> tempList = merchantDao.queryAll(sb.toString());
			List<OrgBean> orgList = orgDao.queryAll(OrgBean.class);
			if (tempList != null && tempList.size() > 0) {
				for (Object obj : tempList) {
					Operators m = (Operators) obj;
					for (OrgBean bean : orgList) {
						if (bean.getOrg_code().equals(m.getOrgCode())) {
							m.setOrgName(bean.getOrg_name());
							// m.setRealName(m.getRealName()+"("+bean.getOrg_name()+")");
						}
					}
					merchants.add(m);
					m = null;
				}
				tempList.clear();
			}

		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public List<Operators> findRecomenderMerchant(Long recomenderId)
			throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		try {
			List<Object> tempList = merchantDao
					.queryAll(" from Merchant t where t.recommenderId="
							+ recomenderId + " order by t.realName ");
			if (tempList != null && tempList.size() > 0) {
				for (Object obj : tempList) {
					Operators m = (Operators) obj;
					merchants.add(m);
				}
			}

		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public List<Operators> findSomeMerchant(String merType, Long merchantId,
			String orgCode) throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		try {
			merchants = merchantDao.listSomeMerchants(merType, merchantId,
					orgCode);

		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public List<Operators> findRecommenders() throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		try {
			merchants = merchantDao.listRecommenders();

		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public void cancelMerchant(Operators merchant, String operators)
			throws ServiceException {
		Operators mer = null;
		try {
			mer = merchantDao.findUniqueMerchantByNo(merchant.getAccountNo());
			if (mer == null) {
				throw new ServiceException("要注销的账号【" + merchant.getAccountNo()
						+ "】不存在");
			}
			mer.setStatus("01");
			merchantDao.editUpdate(mer);
			SysLog sysLog = new SysLog();
			sysLog.setOper_code(SysLogType.OPERATORS_CANCEL.getCode());
			sysLog.setOper_name(SysLogType.OPERATORS_CANCEL.getName());
			sysLog.setOperators(operators);
			sysLog.setLog_context(operators + "注销了代理商【"
					+ merchant.getAccountNo() + "】");
			sysLogDao.editSave(sysLog);
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException("注销账号【" + merchant.getAccountNo()
					+ "】失败");

		}

	}

	@Override
	public void recoverMerchant(Operators merchant, String operators)
			throws ServiceException {
		Operators mer = null;
		try {
			mer = merchantDao.findUniqueMerchantByNo(merchant.getAccountNo());
			if (mer == null) {
				throw new ServiceException("要恢复的账号【" + merchant.getAccountNo()
						+ "】不存在");
			}
			mer.setStatus("00");
			merchantDao.editUpdate(mer);
			SysLog sysLog = new SysLog();
			sysLog.setOper_code(SysLogType.OPERATORS_RECOVER.getCode());
			sysLog.setOper_name(SysLogType.OPERATORS_RECOVER.getName());
			sysLog.setOperators(operators);
			sysLog.setLog_context(operators + "恢复了代理商【"
					+ merchant.getAccountNo() + "】");
			sysLogDao.editSave(sysLog);
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException("恢复账号【" + merchant.getAccountNo()
					+ "】失败");

		}

	}

	public Operators modifyMerchant(Operators merchant, String operators)
			throws ServiceException {

		Operators result = null;
		try {
			result = merchantDao
					.findUniqueMerchantByNo(merchant.getAccountNo());
			if (result == null) {
				throw new ServiceException("代理商【" + merchant.getAccountNo()
						+ "】不存在");
			}
			// result.setOrgCode(merchant.getOrgCode());
			result.setAgentType(merchant.getAgentType());
			result.setRealName(merchant.getRealName());
			result.setBankAcctName(merchant.getBankAcctName());
			result.setAddress(merchant.getAddress());
			result.setBankAcctNo(merchant.getBankAcctNo());
			result.setBankDeposit(merchant.getBankDeposit());
			result.setCardType(merchant.getCardType());
			result.setCardNo(merchant.getCardNo());
			result.setMobile(merchant.getMobile());
			result.setProfitRate(merchant.getProfitRate());
			if (Constance.isNotEmpty(merchant.getRoleType())) {
				result.setRoleType(merchant.getRoleType());
			}
			result.setTelphone(merchant.getTelphone());
			result.setEmail(merchant.getEmail());
			result.setRemark(merchant.getRemark());
			result.setSex(merchant.getSex());
			// result.setBankAcctNo(merchant.getBankAcctNo());
			result.setDtLostmod(new Date());
			result.setOperators(operators);
			merchantDao.editSave(result);

			SysLog sysLog = new SysLog();
			sysLog.setOper_code(SysLogType.OPERATORS_UPDATE.getCode());
			sysLog.setOper_name(SysLogType.OPERATORS_UPDATE.getName());
			sysLog.setOperators(operators);
			sysLog.setLog_context(operators + "修改了代理商【"
					+ merchant.getAccountNo() + "】的基本信息");
			sysLogDao.editSave(sysLog);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new ServiceException("用户信息修改失败");
		}
		return result;
	}

	@Override
	public void delete(Operators merchant, String operators)
			throws ServiceException {
		List<Object> parmas = new ArrayList<Object>();
		parmas.add(merchant.getOrgCode());
		parmas.add(merchant.getId());
		try {
			sqlBaseDao.deleteBySql(
					"delete from t_merchant_module t where t.merchant_no='"
							+ merchant.getAccountNo() + "'", null);

			sqlBaseDao.deleteBySql(
					"delete from t_profit_rule t where t.merchant_id="
							+ merchant.getId() + "", null);
			merchantDao.delete(merchant);
			if ("02".equals(merchant.getRoleType())) {
				sqlBaseDao.deleteBySql(
						"update t_merchant t set t.recommender_id=null where t.recommender_id="
								+ merchant.getId(), null);

			}
			sqlBaseDao
					.deleteBySql(
							" delete from t_profit_model_head t where t.org_code=? and t.merchant_id=?  ",
							parmas);
			sqlBaseDao
					.deleteBySql(
							" delete from t_profit_model t where t.profit_model_head_id in(select distinct t.id from t_profit_model_head t where t.org_code=? and t.merchant_id=?  )  ",
							parmas);
			SysLog sysLog = new SysLog();
			sysLog.setOper_code(SysLogType.OPERATORS_DELETE.getCode());
			sysLog.setOper_name(SysLogType.OPERATORS_DELETE.getName());
			sysLog.setOperators(operators);
			sysLog.setLog_context(operators + "删除了代理商【"
					+ merchant.getAccountNo() + "】的密码");
			sysLogDao.editSave(sysLog);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new ServiceException("删除代理商失败");
		}
	}

	@Override
	public Map<String, Operators> listAllMerchants(String merType,
			long merchantId, String orgCode) throws ServiceException {
		List<Object> merchants1 = new ArrayList<Object>();
		List<Operators> merchants2 = new ArrayList<Operators>();
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		try {
			if (Constance.MERCHANT_TYPE_SYSTEM.equals(merType)) {
				merchants1 = merchantDao.queryAll(" from Merchant t ");
				if (merchants1 != null && merchants1.size() > 0) {
					for (Object m : merchants1) {
						Operators merchant = (Operators) m;
						merchantMap.put(merchant.getId() + "", merchant);
					}
				}
			} else {
				merchants2 = merchantDao.listSomeMerchants(merType, merchantId,
						orgCode);
				if (merchants2 != null && merchants2.size() > 0) {
					for (Operators m : merchants2) {
						merchantMap.put(m.getId() + "", m);
					}
				}
			}

		} catch (DaoException e) {
			logger.error(e.getMessage(), e);

			throw new ServiceException(e.getMessage(), e);
		}
		return merchantMap;
	}

	@Override
	public long isDeleted(long merchantId) throws ServiceException {
		long count = 0;
		try {
			count = merchantDao.isDeleted(merchantId);
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return count;
	}

	@Override
	public List<Operators> listAllSubMerchants(long merchantId)
			throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		String sql = "SELECT * FROM t_operators t start WITH id ="
				+ merchantId
				+ " and ( t.role_type = '"
				+ Role.AGENT.getCode()+"' or t.role_type = '"+Role.AGENT_BUSS.getCode() 
				+ "' ) connect BY prior t.id = t.supri_id order by t.id DESC ";
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public Map<String, Operators> listAll() throws ServiceException {
		List<Object> merchants = new ArrayList<Object>();
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		try {
			merchants = merchantDao
					.queryAll(" from Merchant t order by t.realName ");
			if (merchants != null && merchants.size() > 0) {
				for (Object obj : merchants) {
					Operators m = (Operators) obj;
					merchantMap.put(m.getId() + "", m);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询所有代理商信息出错");
		}
		return merchantMap;
	}

	@Override
	public List<MerchantModuleRight> queryMerchantPowerByNo(String accountNo)
			throws ServiceException {
		List<MerchantModuleRight> merchants = new ArrayList<MerchantModuleRight>();
		List<Object> objList = new ArrayList<Object>();
		String sql = "SELECT * FROM t_merchant_module t WHERE t.merchant_no = '"
				+ accountNo + "'";
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator iterator = objList.iterator();
				while (iterator.hasNext()) {
					MerchantModuleRight merchant = new MerchantModuleRight();
					Object[] obj = (Object[]) iterator.next();
					merchant.setModuleCode(obj[1].toString());
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	// 按照操作员的级别查询对应的权限
	public List<Module> queryModuleType(String merType) throws ServiceException {
		List<Module> merchants = new ArrayList<Module>();
		List<Object> objList = new ArrayList<Object>();
		String sql = "SELECT * FROM t_module t WHERE t.role_type LIKE '%"
				+ merType + "%'";
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator iterator = objList.iterator();
				while (iterator.hasNext()) {
					Module merchant = new Module();
					Object[] obj = (Object[]) iterator.next();
					merchant.setModuleCode(obj[1].toString());
					merchant.setModuleName(obj[2].toString());
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	public void editUpdateMerchantPower(String accountNo, String[] list,
			Operators merchant) throws ServiceException {
		// 根据操作员ID查询该操作员拥有的所有权限
		List<MerchantModuleRight> moduleList = null;
		try {
			// 获取到操作员所拥有的所有权限
			moduleList = queryMerchantPowerByNo(accountNo);
			if (moduleList != null && moduleList.size() != 0) {
				sqlBaseDao.deleteBySql(
						"delete from t_merchant_module t where t.merchant_no='"
								+ accountNo + "'", null);

			}

			// 添加
			for (int i = 0; i < list.length; i++) {
				MerchantModuleRight tmr = new MerchantModuleRight();
				tmr.setOperators(merchant.getAccountNo());
				tmr.setModuleCode(list[i]);
				tmr.setMerchantNo(accountNo);

				baseDao.editSave(tmr);
			}

		} catch (DaoException e) {
			throw new ServiceException("修改作员权限失败！ ");
		}
	}

	@Override
	public List<Object> listOperators() throws ServiceException {
		// TODO Auto-generated method stub
		List<Object> operators = new ArrayList<Object>();
		try {
			operators = merchantDao
					.queryAll("from Merchant t where t.merType in('03','04','05')");
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询操作员信息出错");
		}
		return operators;
	}

	@Override
	public List<Object> queryFirstLevelMerchants() throws ServiceException {
		List<Object> firstMers = new ArrayList<Object>();
		try {
			firstMers = merchantDao
					.queryAll("from Merchant t where t.merType='01' and t.superiorId=1 ");
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询一级代理商信息出错");
		}
		return firstMers;
	}

	

	// 查询结算周期
	@Override
	public List<Object> queryCycle() throws ServiceException {
		List<Object> objList = null;
		try {
			objList = merchantDao.queryAll("from Cycleinfo ");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询结算周期信息出错");

		}
		return objList;
	}

	// 查询商户号序列
	@Override
	public synchronized String queryMerByNo(String mcc) throws ServiceException {
		String merchant = "";
		try {
			String hql = " from MccCode m where m.mccCode ='" + mcc + "'  ";

			MccCode tmp = (MccCode) merchantDao.createQueryUniqueResult(hql);
			if (tmp != null) {
				long serial = tmp.getMccSerial();

				long new_serial = serial + 1;// +1修改
				if (new_serial > 9999) {
					throw new ServiceException("编辑商户序列信息出错");
				}
				merchant = Constance.handleStr(new_serial);// 序号
				// ////////加判断大于9999 时，抛出
				tmp.setMccSerial(new_serial);
				merchantDao.editUpdate(tmp);
			} else {
				merchant = Constance.handleStr(1);
			}

		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("编辑商户序列信息出错");
		}
		return merchant;
	}

	// 查询商户号查询商户所有信息
	@Override
	public MerinfoDetail queryMerByMid(String merNo) throws ServiceException {

		MerinfoDetail tmp = null;
		try {

			tmp = merchantDao.queryMerinfoByNo(merNo);
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询商户信息出错");
		}
		return tmp;
	}

	// 商户进件修改
	@Override
	public void updateMerchant(EsmidinfoTmp merinfoTmp, Operators op,
			List<TermBean> termBeanList) throws ServiceException {
		try {
			// 查询商户终端

			if (merinfoTmp != null) {
				
				//一机一码完善后改为待终审
				String merNoStart = Utils.getConfigValue("merNoStart");//一机一码商户开头
				String mid = Constance.Null2EmptyTrim(merinfoTmp.getMid()); 
				String firstMid = mid.substring(0,3);
				
				if(merNoStart.contains(firstMid)){
					merinfoTmp.setFlag(MerchantStatus.S_3.getCode());//待终审	
				}else{
					merinfoTmp.setFlag(MerchantStatus.S_0.getCode());// 默认状态
				}
				
				merchantDao.editUpdate(merinfoTmp);
			}
			if (merinfoTmp.getMerinfos() != null) {// 修改详细信息
				merchantDao.editUpdate(merinfoTmp.getMerinfos());
			}
			if (termBeanList.size() > 0) {// 修改终端详情
				int termCount = 0; // 本次添加的终端数量
				for (TermBean termBean : termBeanList) {
					if (termBean.getTid() != null
							&& !"".equals(termBean.getTid())) {// 有终端号进行修改
						String sql = "UPDATE t_term_info  SET term_addr=?,remark=?,serial_num=?,terminal_name=? WHERE termid=? ";
						List<Object> objList = new ArrayList<Object>();
						objList.add(termBean.getTermAddress());
						objList.add(termBean.getTermNote());
						objList.add(termBean.getSerialNum());
						objList.add(termBean.getTermName());
						objList.add(termBean.getTid());
						sqlBaseDao.deleteBySql(sql, objList);
					} else {// 没有进行添加
						if (termBean == null)
							continue;
						// 添加终端信息表
						Estidinfo estid = new Estidinfo();
						estid.setMid(merinfoTmp.getMid());
						int maxTid = terminalDao.queryMaxTermapply();
						if (maxTid >= 99999999) {
							throw new ServiceException("终端号已达到最大！");
						}
						terminalDao.editTermTid(maxTid + 1);
						String maxNo = Constance.fillTo8(maxTid, 8);
						estid.setTid(maxNo);
						estid.setTidKind(termBean.getTidKind());
						estid.setPinFmt(Terminal.PIN_FMT_TWO.getCode());
						estid.setFlag(TerminalFlag.FLAG_TWO.getCode());
						estid.setEncMethod("0");
						estid.setMacAlg("1");//
						estid.setBatchNo("0");
						estid.setSekIdx("0");
						estid.setSeitStatus("0");
						estid.setLogonStatus("0");
						estid.setHsm_kidx(estid.getMid() + estid.getTid());// 当前终端主密钥在HSM_TMK表当中的索引（密钥名字
						// rsv1
						if (termCount == 0) {
							merinfoTmp.setRsv1(maxNo);
						}
						merchantDao.editSave(estid);

						/** 添加终端关联表 **/
						TermInfo ter = new TermInfo();
						ter.setTermAddr(termBean.getTermAddress());
						ter.setTermId(maxNo);
						ter.setTerminalName(termBean.getTermName());
						ter.setNote(termBean.getTermNote());
						ter.setSerialNum(termBean.getSerialNum());
						ter.setInstallStatus(Terminal.BIND_TWO.getCode());
						merchantDao.editSave(ter);

						termCount++; // 添加完成，终端数量++
					}

				}

			}
			merchantDao.addSyslog(SysLogType.MERCHANT_INFO_CHANGE.getCode(),
					SysLogType.MERCHANT_INFO_CHANGE.getName(),
					op.getAccountNo(), "操作员【" + op.getAccountNo() + "】，修改商户【"
							+ merinfoTmp.getMid() + "】");

		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("修改商户信息出错");
		}
	}

	// 初审
	@Override
	public void checkMerinfoOne(String mer, Operators op, AuditingItem au,
			String[] value) throws ServiceException {

		au.setAudit_code(AuditingType.MERCHANT_AUDITING.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_AUDITING.getName());// 审核名称
		au.setObj_Audited(mer); // 审核对象
		au.setOperators(op.getAccountNo());// 审核操作员
		try {
			merchantDao.editSave(au);// 添加审核

			// 修改商户交易列表

			String hql = " from  EsmidinfoTmp t where t.mid='" + mer + "' ";
			EsmidinfoTmp es = (EsmidinfoTmp) merchantDao
					.createQueryUniqueResult(hql);
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) { // 通过
				es.setFlag(MerchantStatus.S_2.getCode());// 待复审
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.REFUSE.getCode())) {
				es.setFlag(MerchantStatus.S_5.getCode());// 初审未通过
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {
				es.setFlag(MerchantStatus.S_4.getCode());// 信息不完整
			}
			if (value.length > 0) {
				es.setTranList(Utils.editTransType(value));// 修改交易类型
			}

			merchantDao.edit(es);// 修改商户

			merchantDao.addSyslog(SysLogType.MERCHANT_AUDITING.getCode(),
					SysLogType.MERCHANT_AUDITING.getName(), op.getAccountNo(),
					"操作员【" + op.getAccountNo() + "】，初审特约商户【" + mer + "】成功！");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("初审特约商户失败！", e);
			throw new ServiceException("初审特约商户失败！");
		}
	}

	// 业务复审
	@Override
	public void checkMerinfoFour(EsmidinfoTmp tmp, Operators op,
			AuditingItem au, String[] value) throws ServiceException {

		au.setAudit_code(AuditingType.MERCHANT_BUS_AUDITING.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_BUS_AUDITING.getName());// 审核名称
		au.setObj_Audited(tmp.getMid()); // 审核对象
		au.setOperators(op.getAccountNo());// 审核操作员
		try {
			merchantDao.editSave(au);// 添加审核
			// 修改商户交易列表
			String hql = " from  EsmidinfoTmp t where t.mid='" + tmp.getMid()
					+ "' ";
			EsmidinfoTmp es = (EsmidinfoTmp) merchantDao
					.createQueryUniqueResult(hql);
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) { // 通过
				es.setFlag(MerchantStatus.S_3.getCode());// 待终审
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.REFUSE.getCode())) {
				es.setFlag(MerchantStatus.S_11.getCode());// 复审未通过
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {
				es.setFlag(MerchantStatus.S_4.getCode());// 信息不完整
			}
			if (value.length > 0) {
				es.setTranList(Utils.editTransType(value));// 修改交易类型
			}
			es.setMcc(tmp.getMcc());
			merchantDao.edit(es);// 修改商户

			merchantDao.addSyslog(SysLogType.MERCHANT_BUS_AUDITING.getCode(),
					SysLogType.MERCHANT_BUS_AUDITING.getName(),
					op.getAccountNo(), "操作员【" + op.getAccountNo()
							+ "】，业务复审特约商户【" + tmp.getMid() + "】成功！");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("特约商户业务复审失败！", e);
			throw new ServiceException("特约商户业务复审失败！");
		}
	}

	// 复审
	@Override
	public void checkMerinfoTwo(String mer, Operators op, AuditingItem au,
			EsmidinfoMerinfo esMer, String[] value, List<TermBean> terList)
			throws ServiceException {

		au.setAudit_code(AuditingType.MERCHANT_RE_AUDITING.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_RE_AUDITING.getName());// 审核名称
		au.setObj_Audited(mer); // 审核对象
		au.setOperators(op.getAccountNo());// 审核操作员
		try {
			merchantDao.editSave(au);// 添加审核

			// 修改商户交易列表
			String hql = " from  EsmidinfoMerinfo t where t.merchant='" + mer
					+ "' ";
			EsmidinfoMerinfo es = (EsmidinfoMerinfo) merchantDao
					.createQueryUniqueResult(hql);
			es.setAmount1(esMer.getAmount1());
			es.setDayTotalAmt1(esMer.getDayTotalAmt1());
			es.setMonthTotAmt1(esMer.getMonthTotAmt1());
			es.setAmount2(esMer.getAmount2());
			es.setDayTotalAmt2(esMer.getDayTotalAmt2());
			es.setMonthTotAmt3(esMer.getMonthTotAmt3());
			merchantDao.edit(es);
			String hql1 = " from  EsmidinfoTmp t where t.mid='" + mer + "' ";
			EsmidinfoTmp tmp = (EsmidinfoTmp) merchantDao
					.createQueryUniqueResult(hql1);
			
			String auditResult = "";//审核结果中文
			
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) { // 通过
				auditResult = AuditingResultCodeType.PASS.getName();
				tmp.setFlag(MerchantStatus.S_3.getCode());// 待终审
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.REFUSE.getCode())) {// 驳回
				
				auditResult = AuditingResultCodeType.REFUSE.getName();
				// 驳回则验证审核次数，超过则作废

				long times = 0;
				if (!"".equals(Constance.Null2EmptyTrim(tmp.getCycleTime()))) {
					times = tmp.getCycleTime();
				}
				tmp.setCycleTime(times + 1);

				if (times >= Constant.MER_CHECK_TIMES) {
					tmp.setFlag(MerchantStatus.S_15.getCode());// 作废
					// 更改出库状态
					updateAgentIsUsed(mer, es.getAgentID(), terList);

				} else {
					tmp.setFlag(MerchantStatus.S_4.getCode());// 驳回
				}
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {// 直接作废
				
				auditResult = AuditingResultCodeType.INCOMPLETE_INFO.getName();
				tmp.setFlag(MerchantStatus.S_15.getCode());
				// 更改出库状态
				updateAgentIsUsed(mer, es.getAgentID(), terList);
			}
			if (value.length > 0) {
				tmp.setTranList(Utils.editTransType(value));// 修改交易类型
			}

			merchantDao.edit(tmp);// 修改商户

			merchantDao.addSyslog(SysLogType.MERCHANT_RE_AUDITING.getCode(),
					SysLogType.MERCHANT_RE_AUDITING.getName(),
					op.getAccountNo(), "操作员【" + op.getAccountNo() + "】，复审特约商户【"
							+ mer + "】完成,审核结果:【"+auditResult+"】");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("复审特约商户失败！", e);
			throw new ServiceException("复审特约商户失败！");
		}
	}

	// 终审
	//一机一码终审
	@Override
	public void checkMerinfoThree(EsmidinfoTmp mer, Operators op,
			AuditingItem au, EsmidinfoMerinfo detailMer, List<TermBean> terList)
			throws Exception {

		au.setAudit_code(AuditingType.MERCHANT_LAST_AUDITING.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_LAST_AUDITING.getName());// 审核名称
		au.setOperators(op.getAccountNo());// 审核操作员
		String tellerOps = null;
		try {
			String hql1 = " from  EsmidinfoTmp t where t.mid='" + mer.getMid()
					+ "' ";
			EsmidinfoTmp tmp = (EsmidinfoTmp) merchantDao
					.createQueryUniqueResult(hql1);
			String hql2 = " from  EsmidinfoMerinfo t where t.merchant='"
					+ mer.getMid() + "' ";
			EsmidinfoMerinfo esMer = (EsmidinfoMerinfo) merchantDao
					.createQueryUniqueResult(hql2);
			String beforeMer = queryMerByNo(tmp.getMcc());

			String tmpMid = tmp.getMid();// 临时商户号
			
			String merNoStart = Utils.getConfigValue("merNoStart");//一机一码商户开头
			String merchantNo = "";
			
			String firstMid = tmpMid.substring(0,3);
			
			if(!merNoStart.contains(firstMid)){//非一机一码重新生成商户号
				merchantNo = Constance.MERCHANT_NO + esMer.getAreaCode()
				+ tmp.getMcc() + beforeMer;
				if (merchantNo.length() < 15) {
					logger.info("生成的商户号码为" + merchantNo);
					throw new ServiceException("生成商户号失败，请重新录入！");
				}
				
			}else{//一机一码 不修改商户号
				merchantNo = tmpMid;
			}
			 
			au.setObj_Audited(mer.getMid()); // 审核对象
			merchantDao.editSave(au);// 添加审核
			

			String auditResult = "";//审核结果中文
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) { // 通过
				
				auditResult = AuditingResultCodeType.PASS.getName();

				tellerOps = String.valueOf(MerchantStatus.S_1.getCode());// 终审通过
				//获取10位随机密码
				String password = Utils.getpass(10);
				op.setPwd(password);
				// 添加操作员
				
				agentService.addOperators(op, tmp, esMer, merchantNo);

				
				if(!merNoStart.contains(firstMid)){//非一机一码需要更新终端号
					
					// 修改终端
					List<Object> esList = merchantDao
							.queryAll("from Estidinfo e where e.mid='" + tmpMid
									+ "'");
					for (Object object : esList) {// 修改该商户下的终端
						int maxTid = terminalDao.queryMaxTermapply();
						if (maxTid >= 99999999) {
							throw new ServiceException("终端号已达到最大！");
						}
						terminalDao.editTermTid(maxTid + 1);
						String maxNo = Constance.fillTo8(maxTid, 8);// 生成终端
						Estidinfo et = (Estidinfo) object;
						// 修改终端信息
						String updateTerSql = "update estidinfo set mid='"
								+ merchantNo + "',tid='" + maxNo + "',HSM_KIDX='"
								+ merchantNo + maxNo + "' where tid='"
								+ et.getTid() + "'";
						sqlBaseDao.deleteBySql(updateTerSql, null);
						// 修改终端关联表
						String updateTerApplysql = "update t_term_info set termid='"
								+ maxNo + "' where termid='" + et.getTid() + "'";
						sqlBaseDao.deleteBySql(updateTerApplysql, null);
					}
					
				}
			
				// 同步表(es.... 和es.._merinfo)
				merchantDao.theSameEsTable(merchantNo, tmp.getMid());
				merchantDao.theSameMerTable(merchantNo, tmp.getMid());
				// 修改临时表中状态
				String sql = "update esmidinfo_tmp set mid='" + merchantNo
						+ "',flag=" + MerchantStatus.S_1.getCode()
						+ ",SETTIME = '" + Constance.currTime()
						+ "' where mid='" + tmpMid + "'";
				sqlBaseDao.deleteBySql(sql, null);
				String sql2 = "update esmidinfo_tmp_merinfo set merchant='"
						+ merchantNo + "' ," + " AMOUNT1=" + esMer.getAmount1()
						+ " ,AMOUNT2=" + esMer.getAmount2() + ","
						+ "DAY_TOTAL_AMT1=" + esMer.getDayTotalAmt1()
						+ ",DAY_TOTAL_AMT2=" + esMer.getDayTotalAmt2() + ", "
						+ "MONTH_TOTAL_AMT1=" + esMer.getMonthTotAmt1()
						+ ",MONTH_TOTAL_AMT3=" + esMer.getMonthTotAmt3()
						+ " where merchant='" + tmpMid + "'";
				sqlBaseDao.deleteBySql(sql2, null);

				// 更换审核记录的商户号

				String updateTerSql = "update t_Auditing_item set OBJ_AUDITED='"
						+ merchantNo + "' where OBJ_AUDITED='" + tmpMid + "'";
				sqlBaseDao.deleteBySql(updateTerSql, null);

				
				//把密码发送给客户。
				MessageSend messSend = new MessageSend();
				messSend.setPhoneNumber(esMer.getPersonalPhone());
				messSend.setMesContent("尊敬的用户：您好，您在我司pos运营管理平台的账号是："+merchantNo+",密码为："+password+",访问地址为：http://140.207.82.206:8090/fmposm");
				messSend.setSendFlag("0");
				Date date = new Date();
				messSend.setDtCreate(date);
				messSend.setDtLastmod(date);
				
				baseDao.editSave(messSend);
				
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.REFUSE.getCode())) {//驳回
				
				auditResult = AuditingResultCodeType.REFUSE.getName();

				// 驳回则验证审核次数
				long times = 0;
				if (!"".equals(Constance.Null2EmptyTrim(tmp.getCycleTime()))) {
					times = tmp.getCycleTime();
				}
				if (times >= Constant.MER_CHECK_TIMES) {
					tmp.setFlag(MerchantStatus.S_15.getCode());// 作废
					// 更改出库状态
					updateAgentIsUsed(tmpMid, esMer.getAgentID(), terList);
				} else {
					tmp.setFlag(MerchantStatus.S_4.getCode());// 驳回
				}
				tmp.setCycleTime(times + 1);
				// 修改商户状态
				merchantDao.edit(tmp);

			} else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {
				
				auditResult = AuditingResultCodeType.INCOMPLETE_INFO.getName();
				
				tellerOps = String.valueOf(MerchantStatus.S_15.getCode());// 直接作废
				// 修改商户状态
				updadteMerinfoFlag(tmpMid, tellerOps);
				//修改终端出库状态
				updateAgentIsUsed(tmpMid, esMer.getAgentID(), terList);
			}

			// 日志
			merchantDao.addSyslog(SysLogType.MERCHANT_LAST_AUDITING.getCode(),
					SysLogType.MERCHANT_LAST_AUDITING.getName(),
					op.getAccountNo(), "操作员【" + op.getAccountNo() + "】，终审特约商户【"
							+ mer.getMid() + "】完成,审核结果:【"+auditResult+"】");

		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("终审特约商户失败！", e);
			throw new ServiceException("终审特约商户失败！");
		}
	}


	// 查询审核意见
	@Override
	public List<Object> queryAuditingList(String mid) throws ServiceException {
		String hql = "from AuditingItem a where a.obj_Audited='" + mid
				+ "' order by dt_create ";
		List<Object> objList = null;
		try {
			objList = merchantDao.queryAll(hql);
		} catch (DaoException e) {
			logger.error("查询审核意见失败", e);
			throw new ServiceException("查询审核意见失败");
		}

		return objList;
	}

	@Override
	// 查询商户基本信息(简单信息)
	public Esmidinfo queryEsmidinfoTmp(String mid) throws ServiceException {
		String sql = "SELECT e.mid,e.mer_name,e.flag,e.Inter_Contact,e.tel,m.ternum FROM esmidinfo e INNER JOIN esmidinfo_merinfo m ON e.mid =  m.merchant where e.mid = '"
				+ mid + "'";
		Esmidinfo esmidinfo = new Esmidinfo();
		try {
			Object[] obj = (Object[]) merchantDao
					.createSQLQueryUniqueResult(sql);
			if (obj != null) {
				esmidinfo.setMid(String.valueOf(obj[0]));
				esmidinfo.setMerName(obj[1].toString());
				esmidinfo.setFlagName(MerchantStatus.valueOfCode(
						Integer.valueOf(obj[2].toString())).getName());
				esmidinfo.setInsertContact(obj[3].toString());
				esmidinfo.setTel(obj[4].toString());
				esmidinfo.setTerNums(Constance.Null2EmptyTrim(obj[5]));
			}
		} catch (DaoException e) {
			logger.error("查询商户基本信息失败", e);
			throw new ServiceException("查询商户基本信息失败");
		}
		return esmidinfo;
	}
	
	@Override
	public Esmidinfo queryMerinfobyid(String id) throws ServiceException {

		Esmidinfo sett = new Esmidinfo();
		try {
			sett = merchantDao.queryMerinfobyid(id);
		} catch (DaoException e) {
			logger.debug(e.getMessage());

			throw new ServiceException("查询结算信息失败~！");
		}

		return sett;
	}
	
	@Override
	// 查询商户关联信息
	public EsmidinfoMerinfo queryEsmidinfoMerinfo(String mid)
			throws ServiceException {
		String sql = "SELECT m.card_no,m.business_licences,m.merchant,e.acc_no FROM  esmidinfo_merinfo m,esmidinfo e   where e.mid=m.merchant and m.merchant = '"
				+ mid + "'";
		EsmidinfoMerinfo esmidinfo = new EsmidinfoMerinfo();
		try {
			Object[] obj = (Object[]) merchantDao
					.createSQLQueryUniqueResult(sql);
			if (obj != null) {
				esmidinfo.setCardNo(String.valueOf(obj[0]));
				esmidinfo.setBusinessLicences(obj[1].toString());
				esmidinfo.setMerchant(obj[2].toString());
				esmidinfo.setAccno(obj[3].toString());
			}
		} catch (DaoException e) {
			logger.error("查询商户基本信息失败", e);
			throw new ServiceException("查询商户基本信息失败");
		}
		return esmidinfo;
	}

	@Override
	public List<Operators> listOperatorsAgent(String orgCode)
			throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		try {
			List<Object> tempList = null;
			if (orgCode != null) {
				tempList = merchantDao
						.queryAll(" from Operators o where o.orgCode = '"
								+ orgCode + "' AND o.roleType<>'15'  ");
			} else {
				tempList = merchantDao
						.queryAll(" from Operators o where o.roleType<>'15' ");
			}
			if (tempList != null && tempList.size() > 0) {
				for (Object obj : tempList) {
					Operators m = (Operators) obj;
					merchants.add(m);
				}
			}

		} catch (DaoException e) {
			logger.error("查询商户基本信息失败", e);
			throw new ServiceException("查询商户基本信息失败");
		}
		return merchants;
	}

	// 查询商户信息（临时表）
	@Override
	public EsmidinfoTmp queryMerinfoTmp(String mid) throws ServiceException {
		EsmidinfoTmp tmp = null;
		EsmidinfoMerinfo merTmp = null;
		try {
			String hql = "from EsmidinfoTmp tmp where tmp.mid='" + mid + "'";
			tmp = (EsmidinfoTmp) merchantDao.createQueryUniqueResult(hql);// 信息

			String hql1 = "from EsmidinfoMerinfo tmp where tmp.merchant='"
					+ mid + "'";
			merTmp = (EsmidinfoMerinfo) merchantDao
					.createQueryUniqueResult(hql1);// 详细信息
			if (tmp != null && merTmp != null) {
				tmp.setMerinfos(merTmp);//
			}
			// 查询终端
			List<TermBean> terList = terminalDao.queryTerByMid(mid);
			if (terList.size() > 0 && tmp != null) {
				tmp.setTerBean(terList);
			}
		} catch (DaoException e) {
			logger.error("查询商户基本信息失败", e);
			throw new ServiceException("查询商户基本信息失败");
		}
		return tmp;
	}

	// 根据mcc查询行业类别
	@Override
	public String queryMccTypeByCode(String code) throws ServiceException {
		String result = "";
		String hql = " select mt.mccTypeCode from  MccType mt ,MccCode mc where mc.mccType=mt.mccTypeCode and mc.mccCode='"
				+ code + "'";
		try {
			result = (String) merchantDao.createQueryUniqueResult(hql);
			/*
			 * if(mcc!=null){ result=mcc.getMccTypeCode(); }
			 */
		} catch (DaoException e) {
			logger.error("加载商户信息失败", e);
			throw new ServiceException("加载商户基本信息失败");
		}
		return result;
	}

	// 根据银行查询省份城市银行
	@Override
	public String[] queryBackBranch(String backBranchId)
			throws ServiceException {
		String[] str = new String[3];
		try {
			String hql = "from PayBank p where p.bankBranchId='" + backBranchId
					+ "'";
			PayBank pb = (PayBank) merchantDao.createQueryUniqueResult(hql);
			if (pb != null) {
				str[0] = pb.getProvinceId();
				str[1] = pb.getCityId();
				str[2] = pb.getBankId();
			}
		} catch (DaoException e) {
			logger.error("加载商户信息失败", e);
			throw new ServiceException("加载商户基本信息失败");
		}
		return str;
	}

	// 通过客户号查询终端号
	@Override
	public List<Object> queryYjPosAgent(String id) throws ServiceException {
		String hql = "from YjPosAgent a where a.agentId='" + id + "'";
		List<Object> objList = null;
		try {
			objList = merchantDao.queryAll(hql);
		} catch (DaoException e) {
			logger.error("通过客户号查询终端号", e);
			throw new ServiceException("通过客户号查询终端号");
		}
		return objList;
	}

	// 修改商户状态
	@Override
	public void updadteMerinfoFlag(String mid, String flag)
			throws ServiceException {
		try {
			String sql = "update esmidinfo_tmp set flag='" + flag
					+ "' where mid='" + mid + "'";
			sqlBaseDao.deleteBySql(sql, null);
		} catch (DaoException e) {
			logger.error("修改商户状态失败", e);
			throw new ServiceException("修改商户状态失败");
		}
	}
	@Override
	public boolean checkStatus(String mid, String dealCode){
	    try {
                String sql = "SELECT status FROM T_MERINFO_CHANGE M WHERE M .mid = ? ORDER BY M.DT_CREATE_TIME DESC";
                Object[] params={mid};
                List<?> list=sqlBaseDao.queryAll(sql,params);
                if(null != list && list.size() > 0){
                    String status = (String) list.get(0);
                    if(status.equals("W") || status.equals("Z")){
                        return true;
                    }
                }
                return false;
            } catch (DaoException e) {
                e.printStackTrace();
            }
        return false;
	    
	}

	@Override
	public int initOpePwdErrTimes() throws ServiceException {
		int total = 0;
		try {
			String sql = " UPDATE t_operators s SET s.pwd_err_times=0 WHERE s.pwd_err_times>0 ";
			total = sqlBaseDao.deleteBySql(sql, null);
			logger.info("############总计【" + total + "】个操作员的密码被解锁###########");
		} catch (DaoException e) {
			logger.error("操作员密码错误次数当日清零出错", e);
			throw new ServiceException("操作员密码错误次数当日清零出错");
		}

		return total;
	}

	@Override
	public String insertMerinfoChange(MerinfoChange merinfoChange,TblEditMchtInf merinfoEdit,TblMchtInf merinfo, Operators op)
			throws ServiceException {
		
	
		String res="";
		try {
		//	merchantDao.editSave(merinfoChange);
		        if(merinfoChange.getDealCode().equals("C1")){
		            merchantDao.addSyslog(SysLogType.MERINFO_CHANGE_BASE_INFO.getCode(),
                                    SysLogType.MERINFO_CHANGE_BASE_INFO.getName(),
                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                    + merinfoChange.getMid() + "】的商户号" + "基本信息");
                        }
		        if(merinfoChange.getDealCode().equals("C2")){
		            merchantDao.addSyslog(
                                    SysLogType.MERINFO_CHANGE_SETTING.getCode(),
                                    SysLogType.MERINFO_CHANGE_SETTING.getName(),
                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                    + merinfoChange.getMid() + "】的商户号" + "结算信息");
	                }
		        if(merinfoChange.getDealCode().equals("C3")){
		        ////终端信息
                        List<TblEditTermInf> terminList=merinfoEdit.getTerminfoList();
                        if(null!=terminList && terminList.size()>0){
                                int i=1;
                                for (TblEditTermInf tb:terminList) {
                                        TblEditTermInfId tb_id=new TblEditTermInfId();
                                        String terId;
                                        if(i<10){
                                        	terId="0000000"+i;
                                        }else if(i>10 && i<100){
                                        	terId="000000"+i;
                                        }else {
                                        	terId="00000"+i;
                                        }

                                        tb_id.setMchtCd(merinfoChange.getMid());//商户号
                                        tb_id.setTermId(terId); //终端号码
                                        tb.setId(tb_id);
                                        tb.setBelong("1");
                                        tb.setBelongSub(String.valueOf(op.getOrgCode()));
                                        tb.setStatus("10");//审核的时候根据商户号和status=10得到需要增加的机器（TblEditTermInfId）
                                        tb.setDeviceCd("YJ");//默认sn号码
                                        tb.setRecCrtTs(new Date());//记录时间
                                        tb.setDialOut("60000");//终端呼出号码，默认暂定无用处
                                        tb.setTmnlMoneyIntype("1");//押金收取方式 0按照商户 1按照终端
                                        baseDao.editSave(tb);
                                        
                                        //终端风控信息
                                        TblTermRiskCfg ttr=merinfo.getTerminfoRisk();
                                        if(ttr!=null){//风控信息不为空
                                                for (int j = 0; j < 2; j++) { //借记卡01、贷记卡 00风控规则
                                                        
                                                        TblEditTermRiskCfgId  terRiskId=new TblEditTermRiskCfgId();
                                                        if(j==0)//判断卡类型
                                                                        terRiskId.setCardType("00");
                                                        else 
                                                                        terRiskId.setCardType("01");
                                                        terRiskId.setMchtCd(merinfoChange.getMid());//商户号
                                                        terRiskId.setTermId(terId);//终端号
                                                        TblEditTermRiskCfg terRisk=new TblEditTermRiskCfg();
                                                        terRisk.setId(terRiskId);
                                                        terRisk.setAccpetStartTime(ttr.getAccpetStartTime()); //营业开始时间
                                                        terRisk.setAccpetEndTime(ttr.getAccpetEndTime()); //营业结束时间
                                                        terRisk.setControlWay("1,2");//控制方式
                                                        terRisk.setTotalPeriod("1");//周期
                                                        terRisk.setRecCrtTs(new Date());//录入时间
                                                        terRisk.setRecOprId("I");//插入操作标识符
                                                        terRisk.setRecUpdOpr(String.valueOf(op.getId()));//操作员
                                                        terRisk.setOperIn("I");//插入
                                                        baseDao.editSave(terRisk);
                                                    }
                                            }else{
                                                    return MerinfoChangeReturninfo.S_7.getName();
                                            }
                                            i++;
                                    }
                                merchantDao.addSyslog(
                                        SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
                                        SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
                                        op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                    + merinfoChange.getMid() + "】的商户号" + "增机申请");
                            }else{
                                    return MerinfoChangeReturninfo.S_2.getName();
                            }
	                }
		        if(merinfoChange.getDealCode().equals("C4")||merinfoChange.getDealCode().equals("C5")||merinfoChange.getDealCode().equals("C6")||merinfoChange.getDealCode().equals("C7")||merinfoChange.getDealCode().equals("10")||merinfoChange.getDealCode().equals("11")){
		            ///////获取产品信息
                            String[] productCode=merinfoEdit.getProductCode();
                            if(null!=productCode && productCode.length>0){
                                    ///////手续费 
                                    List<TblEditMchtBizFee> feeList=merinfoEdit.getFee();
                                    if(null==feeList || feeList.size()<1) return MerinfoChangeReturninfo.S_4.getName();
                                        if (merinfoChange.getDealCode().equals("C6")||merinfoChange.getDealCode().equals("C7")||merinfoChange.getDealCode().equals("10")||merinfoChange.getDealCode().equals("11")) {//只有新增的时候，需要添加产品信息
                                            //添加产品信息
                                            //   for (int j = 0; j < productCode.length; j++) {
                                            Map<String, String> proMap = ConfigMerinfoUtil
                                                    .getPosFunction(productCode[0], false);
                                            Iterator<?> iter = proMap.entrySet().iterator();
                                            while (iter.hasNext()) {
                                                Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
                                                String key = (String) entry.getKey();
                                                TblEditMchtBizDeal tmb1 = new TblEditMchtBizDeal();
                                                tmb1.setMchtCd(merinfo.getId());
                                                if (productCode[0].equals(ConfigMerinfoUtil.T1_FUNCTION)) {//t1
                                                    tmb1.setProdCd(ConfigMerinfoUtil.T1_FUNCTION);
                                                    tmb1.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
                                                } else if (productCode[0].equals(ConfigMerinfoUtil.T0_FUNCTION)) {//t0
                                                    tmb1.setProdCd(ConfigMerinfoUtil.T0_FUNCTION);
                                                    tmb1.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
                                                }else if (productCode[0].equals(ConfigMerinfoUtil.UNIONPAY_FUNCTION)) {//银联扫码
                                                    tmb1.setProdCd(key);
                                                    tmb1.setBizCd("0000000");
                                                }else if (productCode[0].equals(ConfigMerinfoUtil.ZWPAY_FUNCTION)) {//支付宝微信扫码
                                                    tmb1.setProdCd(key);
                                                    tmb1.setBizCd("0000000");
                                                }
                                                tmb1.setTransCd(key);
                                                tmb1.setOperIn("I");
                                                tmb1.setRecUpdOpr(String.valueOf(op.getId()));
                                                tmb1.setRecCrtTs(new Date());
                                                baseDao.editSave(tmb1);
                                           }
                                            
                                        }
                                            //添加手续费
                                            if(productCode[0].equals(ConfigMerinfoUtil.T0_FUNCTION)){ //t0
                                                    long subbizCd=2000;
                                                    for (int k=0;k<4;k++) {
                                                            TblEditMchtBizFee teb=null;
                                                            if(k==0){//借记卡
                                                                    if(merinfoChange.getDealCode().equals("C5")){//t0j修改
                                                                        teb=feeList.get(2);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_23.getName());
                                                                    }
                                                                    if(merinfoChange.getDealCode().equals("C7")){//t0j开通
                                                                        teb=feeList.get(6);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_23.getName());
                                                                    }
                                                                    teb.setSubBizCd("000"+subbizCd);
                                                            }else if(k==1){
                                                                    if(merinfoChange.getDealCode().equals("C5")){//t0d修改
                                                                        teb=feeList.get(3);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_24.getName());
                                                                    }
                                                                    if(merinfoChange.getDealCode().equals("C7")){//t0d开通
                                                                        teb=feeList.get(7);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_24.getName());
                                                                    }
                                                                    teb.setSubBizCd("000"+(subbizCd+1));
                                                                     
                                                            }else {
                                                                    teb=new TblEditMchtBizFee();
                                                                    if(k==2){
                                                                            teb.setSubBizCd("000"+(subbizCd+4));
                                                                    }else{
                                                                            teb.setSubBizCd("000"+(subbizCd+5));
                                                                    }
                                                                    teb.setMchtFeePercent(0d);
                                                                    teb.setMchtFeePctMax(0d);
                                                            }
                                                            teb.setMchtCd(merinfoChange.getMid());//商户号
                                                            teb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
                                                            teb.setMchtFeeMd("0"); ///未知参数不能为空
                                                            teb.setMchtAFeeSame("0"); ///未知参数不能为空
                                                            teb.setMchtAFeeMd("0"); ///未知参数不能为空
                                                            teb.setProdCd(productCode[0]);// 产品编号  T1/T0
                                                            teb.setOperIn("I");
                                                            teb.setRecUpdOpr(String.valueOf(op.getId()));
                                                            teb.setRecCrtTs(new Date());
                                                            baseDao.editSave(teb);
                                                    }
                                            }else if(productCode[0].equals(ConfigMerinfoUtil.T1_FUNCTION) ){//t1
                                                    long subbizCd=1000;
                                                    for (int k=0;k<2;k++) {
                                                            TblEditMchtBizFee teb=null;
                                                            if(k==0){//借记卡手续费
                                                                    if(merinfoChange.getDealCode().equals("C4")){//t1j修改
                                                                        teb=feeList.get(0);
                                                                        if(teb.getMchtFeePercent()<0.45) throw new  ServiceException(MerinfoReturninfo.S_25.getName());
                                                                    }
                                                                    if(merinfoChange.getDealCode().equals("C6")){//t1j开通
                                                                        teb=feeList.get(4);
                                                                        if(teb.getMchtFeePercent()<0.45) throw new  ServiceException(MerinfoReturninfo.S_25.getName());
                                                                    }
                                                                    teb.setSubBizCd("000"+subbizCd);
                                                            }else{//贷记卡手续费
                                                                    if(merinfoChange.getDealCode().equals("C4")){//t1d修改
                                                                        teb=feeList.get(1);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_26.getName());
                                                                    }
                                                                    if(merinfoChange.getDealCode().equals("C6")){//t1d开通
                                                                        teb=feeList.get(5);
                                                                        if(teb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_26.getName());
                                                                    }
                                                                    teb.setSubBizCd("000"+(subbizCd+1));
                                                            }
                                                            teb.setMchtCd(merinfoChange.getMid());//商户号
                                                            teb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
                                                            teb.setMchtFeeMd("0"); ///未知参数不能为空
                                                            teb.setMchtAFeeSame("0"); ///未知参数不能为空
                                                            teb.setMchtAFeeMd("0"); ///未知参数不能为空
                                                            teb.setProdCd(productCode[0]);// 产品编号  T1/T0
                                                            teb.setOperIn("I");
                                                            teb.setRecUpdOpr(String.valueOf(op.getId()));
                                                            teb.setRecCrtTs(new Date());
                                                            baseDao.editSave(teb);
                                                    }
                                            }
                                            else if(productCode[0].equals(ConfigMerinfoUtil.UNIONPAY_FUNCTION) ){//银联扫码
                                            	 for (int k=0;k<2;k++) {
	                                            	TblEditMchtBizFee teb=null;
	                                                teb=feeList.get(8);
	                                                teb.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);//卡类型
	                                                teb.setMchtCd(merinfoChange.getMid());//商户号
	                                                teb.setBizCd("0000000");
	                                                teb.setMchtFeeMd("0"); ///未知参数不能为空
	                                                teb.setMchtAFeeSame("0"); ///未知参数不能为空
	                                                teb.setMchtAFeeMd("0"); ///未知参数不能为空
	                                                if(k==0){
	                                                	 teb.setProdCd("1191");// 产品编号  银联正扫扫码1191
	                                                }else{
	                                                	 teb.setProdCd("1691");// 产品编号  银联反扫扫码1691
	                                                }
	                                                teb.setOperIn("I");
	                                                teb.setRecUpdOpr(String.valueOf(op.getId()));
	                                                teb.setRecCrtTs(new Date());
	                                                baseDao.editSave(teb);
                                            	 }
                                        }
                                          else if(productCode[0].equals(ConfigMerinfoUtil.ZWPAY_FUNCTION) ){//支付宝/微信扫码
                                                for (int k=0;k<4;k++) {
                                                        TblEditMchtBizFee teb=null;
                                                        teb=feeList.get(9);
                                                        if(k==0){//支付宝反扫
                                                             teb.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
                                                             teb.setProdCd("1391");
                                                        }
                                                        else if(k==1){//支付宝正扫
                                                            teb.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
                                                            teb.setProdCd("1591");
                                                        }
                                                        else if(k==2){//微信正扫
                                                            teb.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
                                                            teb.setProdCd("1491");
                                                       }
                                                        else{//微信反扫
                                                            teb.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
                                                            teb.setProdCd("1291");
                                                       }
                                                        teb.setMchtCd(merinfoChange.getMid());//商户号
                                                        teb.setBizCd("0000000");
                                                        teb.setMchtFeeMd("0"); ///未知参数不能为空
                                                        teb.setMchtAFeeSame("0"); ///未知参数不能为空
                                                        teb.setMchtAFeeMd("0"); ///未知参数不能为空
                                                        teb.setOperIn("I");
                                                        teb.setRecUpdOpr(String.valueOf(op.getId()));
                                                        teb.setRecCrtTs(new Date());
                                                        baseDao.editSave(teb);
                                                }
                                        }
                                             
                                    //}
                                    
                                    if(merinfoChange.getDealCode().equals("C4")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_T1_FEE.getCode(),
                                                SysLogType.MERINFO_CHANGE_T1_FEE.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请变更T1手续费成功");
                                    }
                                    if(merinfoChange.getDealCode().equals("C5")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_T0_FEE.getCode(),
                                                SysLogType.MERINFO_CHANGE_T0_FEE.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请变更T0手续费成功");
                                    }
                                    if(merinfoChange.getDealCode().equals("C6")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_OPEN_T1.getCode(),
                                                SysLogType.MERINFO_CHANGE_OPEN_T1.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请T1开通成功");
                                    }
                                    if(merinfoChange.getDealCode().equals("C7")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_OPEN_T0.getCode(),
                                                SysLogType.MERINFO_CHANGE_OPEN_T0.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请T0开通成功");
                                        
                                    }
                                    if(merinfoChange.getDealCode().equals("10")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_OPEN_YL.getCode(),
                                                SysLogType.MERINFO_CHANGE_OPEN_YL.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请银联扫码开通成功");
                                        
                                    }
                                    if(merinfoChange.getDealCode().equals("11")){
                                        merchantDao.addSyslog(
                                                SysLogType.MERINFO_CHANGE_OPEN_ZW.getCode(),
                                                SysLogType.MERINFO_CHANGE_OPEN_ZW.getName(),
                                                op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                                + merinfoChange.getMid() + "】的商户号" + "商户申请支付宝/微信扫码开通成功");
                                        
                                    }
                            }else{
                                    return MerinfoChangeReturninfo.S_3.getName();
                            }
	                }
                        if(merinfoChange.getDealCode().equals("C8")){
                            merchantDao.addSyslog(
                                    SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode(),
                                    SysLogType.MERINFO_CHANGE_ZHUXIAO.getName(),
                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                    + merinfoChange.getMid() + "】的商户号" + "商户终止合同申请成功");
                        }
                        if(merinfoChange.getDealCode().equals("11")){
                            merchantDao.addSyslog(
                                    SysLogType.MERINFO_CHANGE_YUSHOUQUAN.getCode(),
                                    SysLogType.MERINFO_CHANGE_YUSHOUQUAN.getName(),
                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
                                                    + merinfoChange.getMid() + "】的商户号" + "商户开通预授权成功");
                        }
                        
                        
                        if(merinfoChange.getDealCode().equals("C9")){
                        	String dvpBy ="";    //是否法人结算
                        	String accountName=merinfo.getBankAccount().getName();  //账户名称
                        	String userPid ="";//merinfo.getCertifNo();    
                        	String accountNo=merinfoChange.getCreditAccount();  //结算卡号
                            String mobile = merinfo.getK2WorkFlowId().trim();   //手机号
                            
                        	String sql ="  select T.DVP_BY from TBL_MCHT_INF T where mcht_cd=? and T.STATUS<>'02' ";
            				Object[] parmas={merinfo.getId()};
            			    List<Object> merList=pageDao.querySqlAll(sql, parmas);
            			    if(!merList.isEmpty()){
            					Object[] objc= merList.toArray();
            					dvpBy =(String) objc[0];
            					if("1".equals(dvpBy)){
            						userPid=merinfo.getStlmWayDesc();
            					}else{
            						userPid=merinfo.getCertifNo();
            					}
            			    }
           //银联检查改造---------开始----------------------------------------//
            			    
            			 /* //查找商户信息
            			    String hql="from TblMchtInf t where t.id=?";
            			    TblMchtInf tmp=(TblMchtInf) pageDao.createQueryUniqueResult(hql, parmas);
            			  //查找原来结算信息
            			    String hql1="from TblMchtBankAccount t where t.ownerCd=?";
            			    TblMchtBankAccount tmp1=(TblMchtBankAccount) pageDao.createQueryUniqueResult(hql1, parmas);
            			    if(tmp.getContactPhoneNo().equals(mobile) && tmp1.getName().equals(accountName)
            			    		&& tmp1.getAccount().equals(accountNo)  ){
            			    	
            			    	Object[] objc= merList.toArray();
            					dvpBy =(String) objc[0];
            					if("1".equals(dvpBy) ){  //否
            						userPid=merinfo.getStlmWayDesc();
            						if(tmp.getStlmWayDesc().equals(userPid)){
            							List<Object> updlist = new ArrayList<Object>();
		            					String updateSql =" UPDATE  tbl_mcht_inf  SET isgroup=?,K2WORKFLOWID=?,REC_UPD_TS=?,OPER_IN=? WHERE mcht_cd=? ";
		            					updlist.add("B");
		            					updlist.add(mobile);
		            					updlist.add(new Date());
		            					updlist.add("U");
		            					updlist.add(merinfoChange.getMid());
		            					 sqlBaseDao.deleteBySql(updateSql, updlist);
		            					
		                                            merchantDao.addSyslog(
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getCode(),
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getName(),
		                                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
		                                                                + merinfoChange.getMid() + "】的商户号" + "商户等级");
		                                              res = MerinfoChangeReturninfo.S_10.getName();
		                                              merinfoChange.setStatus("Y");
            						}
            						logger.info("==================四要素验证成功===================");
            					}else{ //是
            						userPid=merinfo.getCertifNo();
            						if(tmp.getCertifNo().equals(userPid)){
            							List<Object> updlist = new ArrayList<Object>();
		            					String updateSql =" UPDATE  tbl_mcht_inf  SET isgroup=?,K2WORKFLOWID=?,REC_UPD_TS=?,OPER_IN=? WHERE mcht_cd=? ";
		            					updlist.add("B");
		            					updlist.add(mobile);
		            					updlist.add(new Date());
		            					updlist.add("U");
		            					updlist.add(merinfoChange.getMid());
		            					 sqlBaseDao.deleteBySql(updateSql, updlist);
		            					
		                                            merchantDao.addSyslog(
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getCode(),
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getName(),
		                                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
		                                                                + merinfoChange.getMid() + "】的商户号" + "商户等级");
		                                              res = MerinfoChangeReturninfo.S_10.getName();
		                                              merinfoChange.setStatus("Y");
                					}
            					}
            					logger.info("==================四要素验证成功===================");
            			    }*/
            			    //银联检查改造---------结束----------------------------------------//	    	
							 boolean result = FourElementValidateUtils.sendPayjnlsAuditOfJiean(accountName, userPid, accountNo, mobile);
								if(result){//判断验证的信息
		                        		List<Object> updlist = new ArrayList<Object>();
		            					String updateSql =" UPDATE  tbl_mcht_inf  SET isgroup=?,K2WORKFLOWID=?,REC_UPD_TS=?,OPER_IN=? WHERE mcht_cd=? ";
		            					updlist.add("B");
		            					updlist.add(mobile);
		            					updlist.add(new Date());
		            					updlist.add("U");
		            					updlist.add(merinfoChange.getMid());
		            					 sqlBaseDao.deleteBySql(updateSql, updlist);
		            					
		                                            merchantDao.addSyslog(
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getCode(),
		                                                    SysLogType.CHANGE_MERINFO_GRADE.getName(),
		                                                    op.getAccountNo(), op.getAccountNo() + "申请更改【"
		                                                                + merinfoChange.getMid() + "】的商户号" + "商户等级");
		                                              res = MerinfoChangeReturninfo.S_10.getName();
		                                              merinfoChange.setStatus("Y");
		                                              logger.info("==================四要素验证通过===================");
								}else{
									res =MerinfoChangeReturninfo.S_9.getName();
									merinfoChange.setStatus("N");
									logger.info("==================四要素验证不通过===================");
								}
                        	}
                       
                        if(!merinfoChange.getDealCode().equals("C9")){
                        	merinfoChange.setStatus("W");
                        	 merchantDao.editSave(merinfoChange); 
                        	return MerinfoChangeReturninfo.S_6.getName();
                        }else{
                        	 merchantDao.editSave(merinfoChange); 
                        	return res;
                        }
                    	
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("商户申请更改失败", e);
			throw new ServiceException("商户申请更改失败");
		} 
	 
	}

	@Override
	public MerinfoChange queryMerinfoChangeById(Long id)
			throws ServiceException {
		// TODO Auto-generated method stub
		MerinfoChange merinfo = null;
		try {
			merinfo = merchantDao.queryMerinfoChangeByNo(id);
		} catch (DaoException e) {
			logger.error("查询商户信息变更失败", e);
			throw new ServiceException("查询商户信息变更失败");
		}
		return merinfo;
	}
     //商户信息变更审核
	@Override
	public void checkMerinfoChange(MerinfoChange merinfoChange, Operators op,
			AuditingItem au) throws ServiceException {
		// TODO Auto-generated method stub
		String updateSql = "";
		String updateSqlE = "";
		au.setAudit_code(AuditingType.MERCHANT_CHANGE_AUDITING.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_CHANGE_AUDITING.getName());// 审核名称
		au.setObj_Audited(merinfoChange.getMid()); // 审核对象
		au.setOperators(op.getAccountNo());// 审核操作员

		try {
			merchantDao.editSave(au);// 添加审核
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) {

				if (merinfoChange.getDealCode().equals("C1")) {
					updateSql = "update esmidinfo_tmp set addr='"
							+ merinfoChange.getAddr() + "',eng_name='"
							+ merinfoChange.getEngName() + "',eng_br_name='"
							+ merinfoChange.getEngBrName() + "' where mid='"
							+ merinfoChange.getMid() + "'";

					updateSqlE = "update Esmidinfo set addr='"
							+ merinfoChange.getAddr() + "',eng_name='"
							+ merinfoChange.getEngName() + "',eng_br_name='"
							+ merinfoChange.getEngBrName() + "' where mid='"
							+ merinfoChange.getMid() + "'";

				} else if (merinfoChange.getDealCode().equals("C2")) {
					updateSql = "update esmidinfo_tmp set contact='"
							+ merinfoChange.getContact() + "',ACC_BANK='"
							+ merinfoChange.getAccBank() + "',ACC_NO='"
							+ merinfoChange.getAccNo() + "',SETT_BANK_ID='"
							+ merinfoChange.getSettBankId() 
							+"',acc_type='"+merinfoChange.getAcctType()
							+ "' where mid='"
							+ merinfoChange.getMid() + "'";

					updateSqlE = "update Esmidinfo set contact='"
							+ merinfoChange.getContact() + "',ACC_BANK='"
							+ merinfoChange.getAccBank() + "',ACC_NO='"
							+ merinfoChange.getAccNo() + "',SETT_BANK_ID='"
							+ merinfoChange.getSettBankId() 
							+"',acc_type='"+merinfoChange.getAcctType()
							+ "' where mid='"
							+ merinfoChange.getMid() + "'";

				} else if (merinfoChange.getDealCode().equals("C3")) {
					updateSql = "update esmidinfo_tmp set COMM_MODE='"
							+ merinfoChange.getCommMode() + "',COMM_AMT="
							+ merinfoChange.getCommAmt() + ",COMM_RATE="
							+ merinfoChange.getCommRate() + " where mid='"
							+ merinfoChange.getMid() + "'";

					updateSqlE = "update Esmidinfo set COMM_MODE='"
							+ merinfoChange.getCommMode() + "',COMM_AMT="
							+ merinfoChange.getCommAmt() + ",COMM_RATE="
							+ merinfoChange.getCommRate() + " where mid='"
							+ merinfoChange.getMid() + "'";

				} else if (merinfoChange.getDealCode().equals("C4")) {
					updateSql = "update ESMIDINFO_tmp_merinfo set AMOUNT1='"
							+ merinfoChange.getAmount1() + "',AMOUNT2="
							+ merinfoChange.getAmount2() + ",DAY_TOTAL_AMT1="
							+ merinfoChange.getDayAmount1()
							+ ",DAY_TOTAL_AMT2="
							+ merinfoChange.getDayAmount2()
							+ ",MONTH_TOTAL_AMT1="
							+ merinfoChange.getMouthAmount1()
							+ ",MONTH_TOTAL_AMT3="
							+ merinfoChange.getMouthAmount1()
							+ " where MERCHANT='" + merinfoChange.getMid()
							+ "'";

					updateSqlE = "update esmidinfo_merinfo set AMOUNT1="
							+ merinfoChange.getAmount1() + ",AMOUNT2="
							+ merinfoChange.getAmount2() + ",DAY_TOTAL_AMT1="
							+ merinfoChange.getDayAmount1()
							+ ",DAY_TOTAL_AMT2="
							+ merinfoChange.getDayAmount2()
							+ ",MONTH_TOTAL_AMT1="
							+ merinfoChange.getMouthAmount1()
							+ ",MONTH_TOTAL_AMT3="
							+ merinfoChange.getMouthAmount1()
							+ " where MERCHANT='" + merinfoChange.getMid()
							+ "'";

				} else if (merinfoChange.getDealCode().equals("C5")) {
					
					String updateTerSql = "update estidinfo  set flag='"
							+ TerminalFlag.FLAG_TWO.getCode()
							+ "' where flag='" + TerminalFlag.FLAG_FOUR.getCode()
							+ "' and mid='" + merinfoChange.getMid()
							+ "'";
					int total=sqlBaseDao.deleteBySql(updateTerSql, null);
					logger.info("########增机申请复审.操作员【"+op.getAccountNo()+"】审核结果【"+au.getResult_code()+"】，商户号【"+merinfoChange.getMid()+"】，更新【"+total+"】个的终端状态为【"+TerminalFlag.FLAG_TWO.getCode()+"】########");
				} else if (merinfoChange.getDealCode().equals("C6")) {
					List<TermBean> terList = terminalDao
							.queryTerByMid(merinfoChange.getMid());
					for (int i = 0; i < terList.size(); i++) {
						merchantDao
								.updateSQLQuery("update yj_pos_info set merc_code='000000000000000',term_code='00000000',is_bind='N' where merc_code='"
										+ merinfoChange.getMid()
										+ "' and term_code='"
										+ terList.get(i).getTid() + "'");
						merchantDao
								.updateSQLQuery("update t_term_info set serial_num='',install_status='N' where termid='"
										+ terList.get(i).getTid() + "'");
						merchantDao
								.updateSQLQuery("update yj_pos_agent set is_used='N' ,remark='"+"由操作员【"+op.getAccountNo()+"】撤销商户【"+merinfoChange.getMid()+"】的序列号' where serial_num='"
										+ terList.get(i).getSerialNum()
										+ "' and agent_id="
										+ merinfoChange.getAgent_id());
						merchantDao
								.updateSQLQuery("update ESTIDINFO set flag="
										+ TerminalFlag.FLAG_FIVE.getCode()
										+ "  where mid='"
										+ merinfoChange.getMid()
										+ "' and tid='"
										+ terList.get(i).getTid() + "'");

					}

					updateSql = "update esmidinfo_tmp set flag=14  where mid='"
							+ merinfoChange.getMid() + "'";

					updateSqlE = "update Esmidinfo set flag=14  where mid='"
							+ merinfoChange.getMid() + "'";

				}else if (merinfoChange.getDealCode().equals("C7")) {
					updateSql = "update esmidinfo_tmp_merinfo set PERAONAL_PHONE='"
							+merinfoChange.getPerPhone()+"' where MERCHANT='"
							+merinfoChange.getMid()+"'";
					updateSqlE = "update esmidinfo_merinfo set PERAONAL_PHONE='"
							+merinfoChange.getPerPhone()+"' where MERCHANT='"
							+merinfoChange.getMid()+"'";
					merchantDao.updateSQLQuery(" update esmidinfo_tmp set MER_BR_NAME='"
							+merinfoChange.getMerBrName()+"' ,TEL='"
							+merinfoChange.getTel()+"' where mid='"
							+merinfoChange.getMid()+"'");
					merchantDao.updateSQLQuery(" update esmidinfo set MER_BR_NAME='"
							+merinfoChange.getMerBrName()+"' ,TEL='"
							+merinfoChange.getTel()+"' where mid='"
							+merinfoChange.getMid()+"'");
				}else if (merinfoChange.getDealCode().equals("C8")) {
					List<TermInfoTmp> terList = terminalDao
							.queryTermInfoTmpByMid(merinfoChange.getMid());
					for (int i = 0; i < terList.size(); i++) {
						merchantDao
								.updateSQLQuery("update yj_pos_info set merc_code='000000000000000',term_code='00000000',is_bind='N' where merc_code='"
										+ merinfoChange.getMid()
										+ "' and term_code='"
										+ terList.get(i).getTermId() + "'");
						merchantDao
								.updateSQLQuery("update t_term_info set serial_num='',install_status='N' where termid='"
										+ terList.get(i).getTermId() + "'");
						merchantDao
								.updateSQLQuery("update yj_pos_agent set is_used='N',remark='"+"由操作员【"+op.getAccountNo()+"】撤销商户【"+merinfoChange.getMid()+"】的序列号'  where serial_num='"
										+ terList.get(i).getSerialNum()
										+ "' and agent_id="
										+ merinfoChange.getAgent_id());
						merchantDao
								.updateSQLQuery("update ESTIDINFO set flag="
										+ TerminalFlag.FLAG_FIVE.getCode()
										+ "  where mid='"
										+ merinfoChange.getMid()
										+ "' and tid='"
										+ terList.get(i).getTermId() + "'");
						merchantDao
								.updateSQLQuery("update t_term_info_tmp set serial_num='',install_status='N' where termid='"
										+terList.get(i).getTermId()+"'");

					}
					
					List< TermBean> tList=terminalDao.queryTerByMid(merinfoChange.getMid());
					boolean flag=false;
					for(int i=0;i<tList.size();i++){//判断该商户下是否还有终端
						if(!Constance.Null2EmptyTrim(tList.get(i).getSerialNum()).equals("")){
							flag=true;
							break;
						}
					}
					
					if(!flag){
						updateSql = "update esmidinfo_tmp set flag=14  where mid='"
								+ merinfoChange.getMid() + "'";

						updateSqlE = "update Esmidinfo set flag=14  where mid='"
								+ merinfoChange.getMid() + "'";
					}
					
					
				}
				if(Constance.isNotEmpty(updateSql)){
					merchantDao.updateSQLQuery(updateSql);
				}
				if(Constance.isNotEmpty(updateSqlE)){

					merchantDao.updateSQLQuery(updateSqlE);
				}
				
				merinfoChange.setStatus("Y");
				merinfoChange.setDtLostmod(new Date());
				merchantDao.editUpdate(merinfoChange);

				if (merinfoChange.getDealCode().equals("C1")) {
					updateSql = "update esmidinfo_tmp set addr='"
							+ merinfoChange.getAddr() + "',eng_name='"
							+ merinfoChange.getEngName() + "',eng_br_name='"
							+ merinfoChange.getEngBrName() + "' where mid='"
							+ merinfoChange.getMid() + "'";

					updateSqlE = "update Esmidinfo set addr='"
							+ merinfoChange.getAddr() + "',eng_name='"
							+ merinfoChange.getEngName() + "',eng_br_name='"
							+ merinfoChange.getEngBrName() + "' where mid='"
							+ merinfoChange.getMid() + "'";

				} else if (merinfoChange.getDealCode().equals("C2")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_SETTING.getCode(),
							SysLogType.MERINFO_CHANGE_SETTING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】变更结算账户成功！");
				} else if (merinfoChange.getDealCode().equals("C3")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_RATE.getCode(),
							SysLogType.MERINFO_CHANGE_RATE.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】变更商户扣率成功！");
				} else if (merinfoChange.getDealCode().equals("C4")) {
					updateSql = "update ESMIDINFO_tmp_merinfo set AMOUNT1='"
							+ merinfoChange.getAmount1() + "',AMOUNT2="
							+ merinfoChange.getAmount2() + ",DAY_TOTAL_AMT1="
							+ merinfoChange.getDayAmount1()
							+ ",DAY_TOTAL_AMT2="
							+ merinfoChange.getDayAmount2()
							+ ",MONTH_TOTAL_AMT1="
							+ merinfoChange.getMouthAmount1()
							+ ",MONTH_TOTAL_AMT3="
							+ merinfoChange.getMouthAmount1()
							+ " where MERCHANT='" + merinfoChange.getMid()
							+ "'";

					updateSqlE = "update esmidinfo_merinfo set AMOUNT1="
							+ merinfoChange.getAmount1() + ",AMOUNT2="
							+ merinfoChange.getAmount2() + ",DAY_TOTAL_AMT1="
							+ merinfoChange.getDayAmount1()
							+ ",DAY_TOTAL_AMT2="
							+ merinfoChange.getDayAmount2()
							+ ",MONTH_TOTAL_AMT1="
							+ merinfoChange.getMouthAmount1()
							+ ",MONTH_TOTAL_AMT3="
							+ merinfoChange.getMouthAmount1()
							+ " where MERCHANT='" + merinfoChange.getMid()
							+ "'";

				} else if (merinfoChange.getDealCode().equals("C5")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
							SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】增机申请成功！");
				} else if (merinfoChange.getDealCode().equals("C6")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode(),
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】终止合同成功！");
				}else if (merinfoChange.getDealCode().equals("C7")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_INFO.getCode(),
							SysLogType.MERINFO_CHANGE_INFO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】基本信息更改成功！");
				}else if (merinfoChange.getDealCode().equals("C8")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getCode(),
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】终端注销成功！");
				}
			}else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {
				merinfoChange.setStatus("N");
				merinfoChange.setDtLostmod(new Date());
				merchantDao.editUpdate(merinfoChange);
				if (merinfoChange.getDealCode().equals("C1")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_AUDITING.getCode(),
							SysLogType.MERINFO_CHANGE_AUDITING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】变更地址被拒绝！");
				} else if (merinfoChange.getDealCode().equals("C2")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_SETTING.getCode(),
							SysLogType.MERINFO_CHANGE_SETTING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】变更结算账户被拒绝！");
				} else if (merinfoChange.getDealCode().equals("C3")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_RATE.getCode(),
							SysLogType.MERINFO_CHANGE_RATE.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】变更商户扣率被拒绝！");
				} else if (merinfoChange.getDealCode().equals("C4")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_JIAOYI.getCode(),
							SysLogType.MERINFO_CHANGE_JIAOYI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】调整交易额度被拒绝！");
				} else if (merinfoChange.getDealCode().equals("C5")) {
					List<Object> terList = merchantDao
							.queryAll("from Estidinfo e where e.mid='"
									+ merinfoChange.getMid() + "'");
					for (Object object : terList) {// 修改该商户下的终端

						Estidinfo et = (Estidinfo) object;
						if (et.getFlag().equals(
								TerminalFlag.FLAG_FOUR.getCode())) {
							TermInfo terInfo = terminalDao.querTermInfo(et
									.getTid());
							merchantDao
									.updateSQLQuery("update yj_pos_info set merc_code='000000000000000',term_code='00000000',is_bind='N' where merc_code='"
											+ merinfoChange.getMid()
											+ "' and term_code='"
											+ et.getTid()
											+ "'");
							merchantDao
									.updateSQLQuery("update t_term_info set serial_num='',install_status='N' where termid='"
											+ et.getTid() + "'");
							merchantDao
									.updateSQLQuery("update ESTIDINFO set flag="
											+ TerminalFlag.FLAG_INVALID
													.getCode()
											+ "  where mid='"
											+ merinfoChange.getMid()
											+ "' and tid='" + et.getTid() + "'");
							merchantDao
									.updateSQLQuery("update yj_pos_agent set is_used='N' where serial_num='"
											+ terInfo.getSerialNum()
											+ "' and agent_id="
											+ merinfoChange.getAgent_id());

						}
					}
					// merchantDao.addSyslog(SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
					// SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
					// op.getAccountNo(),
					// "操作员【"+op.getAccountNo()+"】，初审商户【"+merinfoChange.getMid()+"】增机申请未通过！");
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
							SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】增机申请被拒绝！");
				} else if (merinfoChange.getDealCode().equals("C6")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode(),
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】终止合同被拒绝！");
				}else if (merinfoChange.getDealCode().equals("C7")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_INFO.getCode(),
							SysLogType.MERINFO_CHANGE_INFO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】更改基本信息申请被拒绝！");
				}else if (merinfoChange.getDealCode().equals("C8")) {
					
					sqlBaseDao.deleteBySql("delete t_term_info_tmp t where t.serial_num is not null and t.mid='"+ merinfoChange.getMid()+"'",null);

					
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getCode(),
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，商户【" + merinfoChange.getMid()
									+ "】注销终端申请被拒绝！");
				}
			}

		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("商户审核失败！", e);
			throw new ServiceException("商户审核失败！");
		}
	}

	@Override
	public List<Object> queryAuditingListChange(String mid, String auditingCode)
			throws ServiceException {
		// TODO Auto-generated method stub
		String hql;
		if (auditingCode == null) {
			hql = "from AuditingItem a where a.obj_Audited='" + mid
					+ "' and a.audit_code in ("
					+ AuditingType.MERCHANT_CHANGE_AUDITING.getCode() + ","
					+ AuditingType.MERCHANT_CHANGE_AUDITING_ONE.getCode()
					+ ") order by dt_create ";
		} else {
			hql = "from AuditingItem a where a.obj_Audited='" + mid
					+ "' and a.audit_code=" + auditingCode
					+ " order by dt_create ";
		}
		List<Object> objList = null;
		try {
			objList = merchantDao.queryAll(hql);
		} catch (DaoException e) {
			logger.error("查询变更信息审核意见失败", e);
			throw new ServiceException("查询变更信息审核意见失败");
		}

		return objList;
	}

	@Override
	public void updateMerinfoChange(MerinfoChange merinfoChange)
			throws ServiceException {
		// TODO Auto-generated method stub
		try {
			merchantDao.editUpdate(merinfoChange);
		} catch (DaoException e) {
			logger.error("更新失败", e);
			throw new ServiceException("更新失败");
		}

	}

	@Override
	public MerinfoChange queryUniqueById(Long id) throws ServiceException {
		// TODO Auto-generated method stub
		Object merinofChange = null;
		try {
			merinofChange = merchantDao.loadById(id, MerinfoChange.class);
		} catch (DaoException e) {
			logger.error("查询失败", e);
			throw new ServiceException("查询失败");
		}
		return (MerinfoChange) merinofChange;
	}

	/**
	 * 通过ID查询直接下级代理商
	 */
	@Override
	public List<Operators> listLowOneMerchants(long merchantId)
			throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		String sql = "SELECT * FROM t_operators t where  t.supri_id ="
				+ merchantId + " and t.role_type in('"+ Role.O_MANAGER.getCode()+"','"+Role.AGENT.getCode()+"' ) and flag = '1'  order by t.real_name DESC ";
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchant.setBankDeposit(Constance.Null2EmptyTrim(obj[22]));
					merchant.setBankAcctNo(Constance.Null2EmptyTrim(obj[23]));
					merchant.setBankAcctName(Constance.Null2EmptyTrim(obj[24]));
					
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	/**
	 * 通过ID删除操作员表
	 * 
	 * @param agentId
	 * @param accountNo
	 *            删除人
	 * @return
	 * @throws ServiceException
	 */
	public int deleteAgentMer(long agentId, String accountNo)
			throws ServiceException {

		String sql = "delete from T_OPERATORS where id = " + agentId;
		int i = 0;
		try {
			i = sqlBaseDao.executeBySql(sql);
			merchantDao.addSyslog(SysLogType.OPERATORS_DELETE.getCode(),
					SysLogType.OPERATORS_DELETE.getName(), accountNo, "操作员【"
							+ accountNo + "】删除了用户ID【" + agentId + "】");
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}

		return i;
	}

	/**
	 * 通过ID删除权限
	 * 
	 * @param agentId
	 * @param accountNo
	 *            删除人
	 * @return
	 * @throws ServiceException
	 */
	public int deleteModule(long agentId, String accountNo)
			throws ServiceException {

		String sql = "delete from t_merchant_module where MERCHANT_NO =(select ACCOUNT_NO from T_OPERATORS where id = "
				+ agentId + ")";
		int i = 0;
		try {
			i = sqlBaseDao.executeBySql(sql);
			merchantDao.addSyslog(SysLogType.POWERINFO_DELETE.getCode(),
					SysLogType.POWERINFO_DELETE.getName(), accountNo, "操作员【"
							+ accountNo + "】删除了用户ID【" + agentId + "】的权限");
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}

		return i;
	}

	/**
	 * 通过ID删除分润规则
	 * 
	 * @param agentId
	 * @param accountNo
	 *            删除人
	 * @return
	 * @throws ServiceException
	 */
	public int deleteProfitRule(long agentId, String accountNo)
			throws ServiceException {

		String sql = "delete from t_profit_rule where AGENT_ID =(select ACCOUNT_NO from T_OPERATORS where id = "
				+ agentId + ")";
		int i = 0;
		try {
			i = sqlBaseDao.executeBySql(sql);
			merchantDao.addSyslog(SysLogType.PROFIT_RULE_DELETE.getCode(),
					SysLogType.PROFIT_RULE_DELETE.getName(), accountNo, "操作员【"
							+ accountNo + "】删除了用户ID【" + agentId + "】的分润规则");
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}

		return i;
	}

	/**
	 * 删除操作员表，权限，分润规则
	 * 
	 * @param agentId
	 * @param accountNo
	 * @return
	 * @throws ServiceException
	 */
	@Transactional(rollbackFor = { ServiceException.class })
	public int deleteMerInfo(long agentId, String accountNo,Operators op)
			throws ServiceException {
		int t = 0;
		try {
			deleteModule(agentId, accountNo);	
			// 通过代理商账号删除代理商分润规则
			agentInfoDao.deleteProfitRuleByAgentId(op.getAccountNo() + "");
			// 通过代理商账号删除代理商分润比例
			agentInfoDao.deleteProfitPerByAgentId(op.getAccountNo() + "");
			// 通过代理商id删除代理商
			agentInfoDao.deleteAgentMer(agentId, accountNo);

			merchantDao.addSyslog(SysLogType.OPERATORS_DELETE.getCode(),
					SysLogType.OPERATORS_DELETE.getName(), accountNo, "操作员【"
							+ accountNo + "】删除了代理商ID【" + agentId + "-" + op.getAccountNo() + "】");
			t = 1;
		} catch (DaoException e) {
			logger.error("######代理商删除失败######", e);
			throw new ServiceException("代理商删除失败!");
		} catch (ServiceException e){
			logger.error("######代理商删除失败######", e);
			throw new ServiceException("代理商删除失败!");
		}

		return t;
	}

	@Override
	public void checkMerinfoChangeOne(MerinfoChange merinfoChange,
			Operators op, AuditingItem au) throws ServiceException {
		// TODO Auto-generated method stub
		au.setAudit_code(AuditingType.MERCHANT_CHANGE_AUDITING_ONE.getCode());// 审核编码
		au.setAudit_name(AuditingType.MERCHANT_CHANGE_AUDITING_ONE.getName());// 审核名称
		au.setObj_Audited(merinfoChange.getMid()); // 审核对象
		au.setOperators(op.getAccountNo());// 审核操作员

		try {
			MerinfoDetail merinfoDetail = merchantDao
					.queryMerinfoByNo(merinfoChange.getMid());// 获取agent_id
			merchantDao.editSave(au);// 添加审核
			if (au.getResult_code().equals(
					AuditingResultCodeType.PASS.getCode())) {
				merinfoChange.setStatus("P");
				merinfoChange.setDtLostmod(new Date());
				merchantDao.editUpdate(merinfoChange);
				// merchantDao.updateSQLQuery("update t_merinfo_change set status='P' DT_LASTMOD='"+new
				// Date()+"' where id="+merinfoChange.getId());
				if (merinfoChange.getDealCode().equals("C1")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_AUDITING.getCode(),
							SysLogType.MERINFO_CHANGE_AUDITING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】营业地址变更通过！");
				} else if (merinfoChange.getDealCode().equals("C2")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_SETTING.getCode(),
							SysLogType.MERINFO_CHANGE_SETTING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】变更结算账户通过");
				} else if (merinfoChange.getDealCode().equals("C3")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_RATE.getCode(),
							SysLogType.MERINFO_CHANGE_RATE.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】变更商户扣率通过！");
				} else if (merinfoChange.getDealCode().equals("C4")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_JIAOYI.getCode(),
							SysLogType.MERINFO_CHANGE_JIAOYI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】调整交易额度通过！");
				} else if (merinfoChange.getDealCode().equals("C5")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
							SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】增机申请通过！");
				} else if (merinfoChange.getDealCode().equals("C6")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode(),
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】终止合同申请通过！");
				}else if (merinfoChange.getDealCode().equals("C7")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_INFO.getCode(),
							SysLogType.MERINFO_CHANGE_INFO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】基本信息更改申请通过！");
				}else if (merinfoChange.getDealCode().equals("C8")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getCode(),
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】终端注销申请通过！");
				}
			} else if (au.getResult_code().equals(
					AuditingResultCodeType.INCOMPLETE_INFO.getCode())) {
				merinfoChange.setStatus("O");
				merinfoChange.setDtLostmod(new Date());
				merchantDao.editUpdate(merinfoChange);
				// merchantDao.updateSQLQuery("update t_merinfo_change set status='O' DT_LASTMOD='"+new
				// Date()+"'  where id="+merinfoChange.getId());
				if (merinfoChange.getDealCode().equals("C1")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_AUDITING.getCode(),
							SysLogType.MERINFO_CHANGE_AUDITING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】营业地址变更未通过！");
				} else if (merinfoChange.getDealCode().equals("C2")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_SETTING.getCode(),
							SysLogType.MERINFO_CHANGE_SETTING.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】变更结算账户未通过！");
				} else if (merinfoChange.getDealCode().equals("C3")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_RATE.getCode(),
							SysLogType.MERINFO_CHANGE_RATE.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】变更商户扣率未通过！");
				} else if (merinfoChange.getDealCode().equals("C4")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_JIAOYI.getCode(),
							SysLogType.MERINFO_CHANGE_JIAOYI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】调整交易额度未通过！");
				} else if (merinfoChange.getDealCode().equals("C5")) {
					List<Object> terList = merchantDao
							.queryAll("from Estidinfo e where e.mid='"
									+ merinfoChange.getMid() + "'");
					for (Object object : terList) {// 修改该商户下的终端

						Estidinfo et = (Estidinfo) object;
						if (et.getFlag().equals(
								TerminalFlag.FLAG_FOUR.getCode())) {
							TermInfo terInfo = terminalDao.querTermInfo(et
									.getTid());
							merchantDao
									.updateSQLQuery("update yj_pos_info set merc_code='000000000000000',term_code='00000000',is_bind='N' where merc_code='"
											+ merinfoChange.getMid()
											+ "' and term_code='"
											+ et.getTid()
											+ "'");
							merchantDao
									.updateSQLQuery("update t_term_info set serial_num='',install_status='N' where termid='"
											+ et.getTid() + "'");
							merchantDao
									.updateSQLQuery("update ESTIDINFO set flag="
											+ TerminalFlag.FLAG_INVALID
													.getCode()
											+ "  where mid='"
											+ merinfoChange.getMid()
											+ "' and tid='" + et.getTid() + "'");
							merchantDao
									.updateSQLQuery("update yj_pos_agent set is_used='N' where serial_num='"
											+ terInfo.getSerialNum()
											+ "' and agent_id="
											+ merinfoDetail.getAgentId());

						}
					}
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
							SysLogType.MERINFO_CHANGE_ZENGJI.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】增机申请未通过！");
				} else if (merinfoChange.getDealCode().equals("C6")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode(),
							SysLogType.MERINFO_CHANGE_ZHUXIAO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】终止合同申请未通过！");
				}else if (merinfoChange.getDealCode().equals("C7")) {
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_INFO.getCode(),
							SysLogType.MERINFO_CHANGE_INFO.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】基本信息更改申请未通过！");
				}else if (merinfoChange.getDealCode().equals("C8")) {
					
					sqlBaseDao.deleteBySql("delete t_term_info_tmp t where t.serial_num is not null and t.mid='"+ merinfoChange.getMid()+"'",null);
					
					
					merchantDao.addSyslog(
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getCode(),
							SysLogType.MERINFO_CHANGE_ZONGDUAN.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，初审商户【" + merinfoChange.getMid()
									+ "】终端注销申请未通过！");
				}
			}
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("商户初审失败！", e);
			throw new ServiceException("商户初审失败！");
		}
	}

	@Override
	public List<TermBean> queryTermByMid(String mid) throws ServiceException {
		// TODO Auto-generated method stub
		List<TermBean> terList;
		try {
			terList = terminalDao.queryTerByMid(mid);

		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("商户审核失败！", e);
			throw new ServiceException("商户审核失败！");
		}
		return terList;
	}

	
	/*
	 * @Override public void checkMerinfoChangeTerm( Operators op,MerinfoChange
	 * merinfoChange,AuditingItem au) throws ServiceException { // TODO
	 * Auto-generated method stub try{
	 * if(au.getResult_code().equals(AuditingResultCodeType.PASS.getCode())){
	 * merinfoChange.setStatus("Y"); merinfoChange.setDtLostmod(new Date());
	 * merchantDao.editUpdate(merinfoChange); List<Object>
	 * terList=merchantDao.queryAll
	 * ("from Estidinfo e where e.mid='"+merinfoChange.getMid()+"'"); for
	 * (Object object : terList) {//修改该商户下的终端 int
	 * maxTid=terminalDao.queryMaxTermapply(); if(maxTid >= 99999999){ throw new
	 * ServiceException("终端号已达到最大！"); } terminalDao.editTermTid(maxTid+1);
	 * 
	 * Estidinfo et=(Estidinfo)object;
	 * if(et.getFlag().equals(TerminalFlag.FLAG_FOUR.getCode())){ //修改终端信息
	 * String
	 * updateTerSql="update estidinfo set flag='"+TerminalFlag.FLAG_TWO.getCode
	 * ()+"' where tid='"+et.getTid()+"' and mid='"+merinfoChange.getMid()+"'";
	 * sqlBaseDao.deleteBySql(updateTerSql,null); }
	 * 
	 * 
	 * merchantDao.addSyslog(SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
	 * SysLogType.MERINFO_CHANGE_ZENGJI.getName(), op.getAccountNo(),
	 * "操作员【"+op.getAccountNo()+"】，商户【"+merinfoChange.getMid()+"】申请增机成功！"); }
	 * }else
	 * if(au.getResult_code().equals(AuditingResultCodeType.INCOMPLETE_INFO
	 * .getCode())){ merinfoChange.setStatus("F");
	 * merinfoChange.setDtLostmod(new Date());
	 * merchantDao.editUpdate(merinfoChange);
	 * merchantDao.addSyslog(SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
	 * SysLogType.MERINFO_CHANGE_ZENGJI.getName(), op.getAccountNo(),
	 * "操作员【"+op.getAccountNo
	 * ()+"】，初审商户【"+merinfoChange.getMid()+"】增机申请未成功，原因信息不完善！"); }else
	 * if(au.getResult_code().equals(AuditingResultCodeType.REFUSE.getCode())){
	 * merinfoChange.setStatus("N"); merinfoChange.setDtLostmod(new Date());
	 * merchantDao.editUpdate(merinfoChange);
	 * merchantDao.addSyslog(SysLogType.MERINFO_CHANGE_ZENGJI.getCode(),
	 * SysLogType.MERINFO_CHANGE_ZENGJI.getName(), op.getAccountNo(),
	 * "操作员【"+op.getAccountNo()+"】，初审商户【"+merinfoChange.getMid()+"】增机申请被拒绝！"); }
	 * }catch (DaoException e) { e.printStackTrace(); logger.error("商户增机失败！",e);
	 * throw new ServiceException("商户增机失败！"); } }
	 */
	/**
	 * 通过商户号修改状态 正式表
	 * 
	 * @param mid
	 * @param flag
	 *            启用1 停用 13
	 * @param accountNo
	 *            当前操作员
	 * @return
	 * @throws ServiceException
	 */
	public int updateMerchantFlag(String mid, int flag, String accountNo)
			throws ServiceException {

		String sql = "update  ESMIDINFO set flag  = '" + flag
				+ "' where mid = '" + mid + "' ";
		int i = 0;
		try {
			String logCode = "";
			String logName = "";
			if (MerchantStatus.S_1.getCode() == flag) {
				logCode = SysLogType.MERCHANT_OPEN.getCode();
				logName = SysLogType.MERCHANT_OPEN.getName();
			} else if (MerchantStatus.S_13.getCode() == flag) {
				logCode = SysLogType.MERCHANT_COLESE.getCode();
				logName = SysLogType.MERCHANT_COLESE.getName();
			} else {
				return i;
			}

			i = sqlBaseDao.executeBySql(sql);
			merchantDao.addSyslog(logCode, logName, accountNo, "操作员【"
					+ accountNo + "】将商户【" + mid + "】状态修改成【" + logName + "】");

		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}

		return i;
	}

	/**
	 * 更新所有终端的出库状态
	 * 
	 * @param mid
	 * @param agentId
	 * @param terList
	 * @return
	 * @throws ServiceException
	 */
	public int updateAgentIsUsed(String mid, long agentId,
			List<TermBean> terList) throws ServiceException {

		String sql = "";
		int i = 0;
		try {
			for (TermBean term : terList) {
				String serialNum = term.getSerialNum();
				sql = "update yj_pos_agent set IS_USED = 'N' where SERIAL_NUM = '"
						+ serialNum + "' and agent_id = " + agentId + "  ";
			}
			sqlBaseDao.deleteBySql(sql, null);
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}

		return i;
	}
	
	
	// 查询代理商可用的MCC集合

	public List<Object> queryMcc4Agent(String accountNo) throws ServiceException {
		List<Object> objList = null;
		try {
			objList = merchantDao.queryAll("from ProfitRule ");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("查询结算周期信息出错");

		}
		return objList;
	}
	
	@Override
	public boolean queryMerinfoChangeByMid(String mid, String flag) throws ServiceException {
		// TODO Auto-generated method stub
		try{
			return merchantDao.queryMerinfoChangeByMid(mid, flag);
		}catch(DaoException e){
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		
	}
	
	
	/**
	 *  直接添加正式商户
	 *  2015/04/21 修改 一机一码走一次终审
	 */
	@Override
	public synchronized void insertMerinfoForReal(EsmidinfoTmp merinfoTmp,
			Operators op, List<TermBean> termBeanList,String[] value, String posBrandCode)
			throws ServiceException {
		try {
			if (merinfoTmp.getMerinfos().getAreaCode() == null
					|| merinfoTmp.getMcc().equals("")) {
				throw new ServiceException("请检查地区码和mcc码！");
			}
			String cardNo = merinfoTmp.getMerinfos().getCardNo();
			int cardCount = merchantDao.checkCardNoTimes(cardNo);
			if (cardCount>=Constant.MER_CARD_TIMES) {
				throw new ServiceException("证件号"+cardNo+"超过使用次数");
			}
			String businessLicences = merinfoTmp.getMerinfos().getBusinessLicences();
			String isCheckBuss =  Utils.getConfigValue("isCheckBusinessLicences");
			int bussCount = merchantDao.checkBusLicencesTimes(businessLicences);
			if (bussCount>=Constant.MER_BUSS_TIMES && Constant.IS_CHECK_MER_BUSS.equals(isCheckBuss)) {
				throw new ServiceException("营业执照号"+businessLicences+"已经使用");
			}
			
			long agentId = op.getId();
			if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){//业务员
				agentId = op.getSuperiorId();
			}
			
			String mid = merinfoTmp.getMid();
		
			merinfoTmp.setCommDivNum(0l);
			merinfoTmp.setDivComm1(0.0);
			merinfoTmp.setDivComm2(0.0);
			merinfoTmp.setDivComm3(0.0);
			merinfoTmp.setDivComm4(0.0);
			merinfoTmp.setDivLwm1(0.0);
			merinfoTmp.setDivLwm2(0.0);
			merinfoTmp.setDivLwm3(0.0);
			merinfoTmp.setDivLwm4(0.0);
			// merinfoTmp.setRsv1("00000000");
			merinfoTmp.setRsv2("N");
			merinfoTmp.setRouteFlag(2l);
			merinfoTmp.setRouteId("312");
			merinfoTmp.setCycleTime(1l);
			merinfoTmp.setPreproFlag(0l);
			merinfoTmp.setTransTimes(5);
			merinfoTmp.setTransTotalAmtDj("10000000");
			merinfoTmp.setTransTotalAmtJj("20000000");
			merinfoTmp.setFlag(Integer.valueOf(MerchantStatus.S_3.getCode()));
			merinfoTmp.setJoinDate(Constance.currTime());// 当前时间
			
			if (value.length > 0) {
				merinfoTmp.setTranList(Utils.editTransType(value));// 修改交易类型
			}

			for (TermBean term : termBeanList) {
				if (term == null)
					continue;
				
				YjPosInfo yjPosInfo=terminalDao.queryYjPosInfo(term.getSerialNum(), posBrandCode);
				// 添加终端信息表
				Estidinfo estid = new Estidinfo();
				

				estid.setTid(term.getTid());
				estid.setMid(mid);
				estid.setTidKind(yjPosInfo.getPosType());
				estid.setPinFmt(Terminal.PIN_FMT_TWO.getCode());
				estid.setFlag(TerminalFlag.FLAG_ONE.getCode());
				estid.setEncMethod("0");
				estid.setMacAlg("1");//
				estid.setBatchNo("0");
				estid.setSekIdx("0");
				estid.setSeitStatus("0");
				estid.setLogonStatus("0");
				estid.setHsm_kidx(mid + term.getTid());// 当前终端主密钥在HSM_TMK表当中的索引（密钥名字

				merchantDao.editSave(estid);

				/** 添加终端关联表 **/
				TermInfo ter = new TermInfo();
				ter.setTermAddr(term.getTermAddress());
				ter.setTermId(term.getTid());
				ter.setTerminalName(term.getTermName());
				ter.setNote(term.getTermNote());
				ter.setSerialNum(term.getSerialNum());
				ter.setInstallStatus(Terminal.BIND_TWO.getCode());
				merchantDao.editSave(ter);
				//修改序列号表
				
				yjPosInfo.setMercCode(mid);
				yjPosInfo.setTermCode(term.getTid());
				yjPosInfo.setIsBind(Terminal.BIND_ONE.getCode());
				baseDao.editUpdate(yjPosInfo);
				// 修改序列号分配表
				YjPosAgent yj = new YjPosAgent();
				String sql = "update  yj_pos_agent  y set y.IS_USED=?,y.OPERATORS=?,y.DT_LASTMOD=?,y.REMARK=? "
						+ "where y.SERIAL_NUM=? and y.AGENT_ID = ? and y.IS_USED = 'N' ";
				List<Object> paramList = new ArrayList<Object>();
				paramList.add("Y");
				paramList.add(op.getAccountNo());
				paramList.add(yj.getDtLostmod());
				paramList.add("操作员"+op.getAccountNo()+"通过录入商户["+mid+"]将终端序列号["+term.getSerialNum()+"]的出库状态改为是");
				paramList.add(term.getSerialNum());
				paramList.add(agentId);
				sqlBaseDao.deleteBySql(sql, paramList);// 修改

			}

			if (merinfoTmp.getMerinfos() != null) {
				merinfoTmp.getMerinfos().setOperators(op.getAccountNo());
				merinfoTmp.getMerinfos().setMerchant(mid);
				merinfoTmp.getMerinfos().setAgentID(agentId);// 默认为当前操作员
				merchantDao.editSave(merinfoTmp.getMerinfos()); // 附加信息
			}

			merchantDao.editSave(merinfoTmp);// 添加商户基本信息
			
/*			//新增至正式的商户表和商户关联表
			merchantDao.theSameEsTable(mid, mid);
			merchantDao.theSameMerTable(mid, mid);

			
			//新增操作员表以及权限
			
			//获取10位随机密码
			String password = Utils.getpass(10);
			
			Operators  ops=new Operators();
			ops.setAccountNo(mid);
			ops.setRealName(merinfoTmp.getMerBrName());
			String  pwd=MD5Utils.MD5Encode(password);
			ops.setPwd(pwd);
			DateFormat df=DateFormat.ZH_DEL_ALL;
			Date newDate=df.toDate(Constance.formateDateTime());
			newDate.setYear(newDate.getYear()+1);
			ops.setValidEndDate(df.toString(newDate));//操作员有效期
			ops.setValidStartDate(Constance.formateDateTime());//有效期开始日期
			ops.setMobile(merinfoTmp.getMerinfos().getPersonalPhone());//法人手机号
			ops.setOrgCode(merinfoTmp.getBelongBranch());//机构
			ops.setStatus(OperatorsStatus.OK.getCode());//状态
			ops.setSuperiorId(op.getId());//父类id
			ops.setOperators(op.getAccountNo());//op
			ops.setRoleType(Role.MERCHANT.getCode());//角色类别
			ops.setFlag(op.getFlag());
			ops.setMerberFlag(op.getMerberFlag());
			
			String time = "";
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			time = sdf.format(dt);
			ops.setUpdatePWD(time);
			//ops.setRealName(mer.getMerName());
			ops.setSex("1");
			baseDao.editSave(ops);
		
			//添加商户权限（初始4个权限）
			for (int i = 0; i < 4; i++) {
				MerchantModuleRight  mmr= new MerchantModuleRight();
				mmr.setMerchantNo(mid);
				mmr.setOperators(op.getAccountNo());
				if(i==0){
					mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());//商户查询
				}else if(i==1){
					mmr.setModuleCode(MerinfoModule.C_04_M_01.getName());//交易查询
				}else if(i==2){
					mmr.setModuleCode(MerinfoModule.C_04_M_02.getName());//历史交易查询
				}else if(i==3){
					mmr.setModuleCode(MerinfoModule.C_07_M_02.getName());//终端查询
				}
				agentDao.editSave(mmr);
			}*/
			

			/** 添加终端记录日志 **/
			merchantDao
					.addSyslog(SysLogType.MERCHANT_ADD.getCode(),
							SysLogType.MERCHANT_ADD.getName(),
							op.getAccountNo(), "操作员【" + op.getAccountNo()
									+ "】，添加商户【" + mid + "】成功");
			
			
			/*//把密码发送给客户。
			MessageSend messSend = new MessageSend();
			messSend.setPhoneNumber(merinfoTmp.getMerinfos().getPersonalPhone());
			messSend.setMesContent("尊敬的用户：您好，您在我司pos运营管理平台的账号是："+mid+",密码为："+password+",访问地址为：http://140.207.82.206:8090/fmposm");
			messSend.setSendFlag("0");
			Date date = new Date();
			messSend.setDtCreate(date);
			messSend.setDtLastmod(date);
			
			baseDao.editSave(messSend);*/

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException("添加商户信息出错");
		}

	}
	
	
	@Override
	//增加可疑商户
	public  synchronized void saveKyMer(susesMerinfo sub)
			throws ServiceException {
		
		try {
			baseDao.editSave(sub);
				/**添加记录日志**/
				//baseDao.addSyslog(SysLogType.TERM_ADD.getCode(), SysLogType.TERM_ADD.getName(), account, "操作员"+account+"添加终端成功，终端号【"+maxNo+"】");
	
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("添加可以商户出错！");
		}
		
	}
	
	
	@Override
	//查询所有可用的的代理商
	public List<Operators> listAllAgent() throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		
		String sql = "SELECT * FROM t_operators t where  t.role_type in('"+ Role.O_MANAGER.getCode()+"','"+Role.AGENT.getCode()+"' ) and flag = '1' ";
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchant.setBankDeposit(Constance.Null2EmptyTrim(obj[22]));
					merchant.setBankAcctNo(Constance.Null2EmptyTrim(obj[23]));
					merchant.setBankAcctName(Constance.Null2EmptyTrim(obj[24]));
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}

	@Override
	//查询所有代理商 type 为 03
	public List<Operators> queryLowOneAgent(String supId) throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		
		String sql = "SELECT * FROM t_operators t where  t.role_type = '03' and t.supri_id = " + supId;
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}
	
/*********************************************紧急开发*******************************************************/
	/**
	 * 进件保存商户信息
	 * @param merchantInfo  页面商户信息
	 * @param op 操作员信息
	 * @return void 
	 * @author zbl
	 * */
		@Override
		public synchronized String insertMerinfo(TblEditMchtInf merinfo,Operators op)
				throws ServiceException {
			try {
				String str=validateForm(merinfo, op);//校验
				if(null!=str) return str;
				   
				 
				String validateStr=validateCount(merinfo,op);//
				if(null!=validateStr) return validateStr;
				
				String validate=validateExist(merinfo,op);//校验 身份证，银行卡，营业执照，非法人身份证是否被风控
				if(null!=validate) return validate;
				
				String sql="SELECT T.INS_COMPANY_CD FROM TBL_INS_INF T WHERE T.INS_ID_CD=? AND INS_TYPE=1";
				Object[] params={op.getOrgCode()};
				Object parentOrg=sqlBaseDao.findObj(sql, params);
				//商户基础数据信息 
				merinfo.setUcBccd(op.getOrgCode().substring(0, 4)+merinfo.getUcBccd());//32域
				if( merinfo.getUcBccd().trim().length()<5 || merinfo.getUcBccd().trim().indexOf("null")>-1) return MerinfoReturninfo.S_27.getName();
				merinfo.setMcc(merinfo.getUpMccCd());//mcc
				merinfo.setUpMccCd(merinfo.getUpMccCd());//mcc
				String applDate = DateUtil.getDate(new Date(), 0, "yyyy-MM-dd");
				merinfo.setNameBusi(merinfo.getNameBusi().trim());//去除空格
				merinfo.setApplDate(applDate); //申请时间
				merinfo.setSn("0000");
				merinfo.setAipBranCd(String.valueOf(parentOrg));//所属分公司
				if("2".equals(merinfo.getGroupCD()) && (Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
						|| Role.OPERATORS_LEAD.getCode().equals(op.getRoleType()))){ ////所属机构
					merinfo.setBankBelongCd(merinfo.getBankBelongCd());
				}else{
					merinfo.setBankBelongCd(op.getOrgCode()); 
				}
				merinfo.setOriChnl("0");//商户来源渠道 0主动发展
				merinfo.setDvpBy(merinfo.getDvpBy());//推荐人----  已用作判断是否法人结算账户
				merinfo.setUpBccd("850");//商户编码前三位机构代码
				merinfo.setBillingType("00");//商户计费类型
				//merinfo.setBillingLevel(merinfo.getBillingLevel());//商户计费档次
				merinfo.setApprovalUserName(merinfo.getApprovalUserName());//--现在保存 账户属性 0 私人账户   1 企业账户
				merinfo.setNationCd(merinfo.getNationCd().trim()); //商户注册地址默---- 已用作商户类型  对公或对私
				merinfo.setRecUpdOpr(String.valueOf(op.getId()));// 操作员id
				merinfo.setOperIn("I");
				if("2".equals(merinfo.getGroupCD())){
					merinfo.setStatus(MerinfoStatus.S_14.getCode());//直营初始默认状态14
				}else{
				merinfo.setStatus(MerinfoStatus.S_1.getCode());//初始默认状态00
				}
				merinfo.setRecCrtTs(new Date());//添加时间
				if(null==merinfo.getGroupCD() || merinfo.getGroupCD().trim().length()<1){
					merinfo.setGroupCD(op.getGroupCd()); //商户直连间连选择  默认为间连
				}else{
					merinfo.setGroupCD(merinfo.getGroupCD()); //商户直连间连选择
				}
				if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){ //业务员取上级id
					merinfo.setExt1(String.valueOf(op.getSuperiorId()));
				}else if(Role.OPERATORS_COMM.getCode().equals(op.getRoleType())){ //运营专员
					if("2".equals(merinfo.getGroupCD())){
						merinfo.setExt1(merinfo.getExt1()); //直营商户可动态选择所属代理商
					}else{
						merinfo.setExt1(String.valueOf(op.getSuperiorId())); //非直营取上级id
					}
				}else if("2".equals(merinfo.getGroupCD()) && Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){ //受理市场运营
					merinfo.setExt1(merinfo.getExt1()); //直营商户可动态选择所属代理商
				}else{
					merinfo.setExt1(String.valueOf(op.getId())); //其他情况保存当前登录人自己
				}
				if("2".equals(merinfo.getGroupCD()) && Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){ ////机构号
					String ext1 = merinfo.getExt1();
					if(ext1 != null && ext1.length() > 0){
						Operators opr = powerInfoService.loadOperatorsById(Long.valueOf(ext1)); 
						if(opr != null){
							merinfo.setUcBccdArea(opr.getOneagentid());
						}
					}
				}else{
					merinfo.setUcBccdArea(op.getOneagentid());	
				}
				//受理市场扩展商户信息
				if("2".equals(op.getGroupCd())){
					TblEditMchtExtendInfo mchtExtendInfo = merinfo.getMchtExtendInfo();
					mchtExtendInfo.setId(merinfo.getId());
					baseDao.editSave(mchtExtendInfo);
					logger.info("-----临时商户扩展信息添加成功-----商户号："+merinfo.getId()+"-----end");
				}
				////终端信息
				List<TblEditTermInf> terminList=merinfo.getTerminfoList();
				if(null!=terminList && terminList.size()>0){
					int i=1;
					for (TblEditTermInf tb:terminList) {
						TblEditTermInfId tb_id=new TblEditTermInfId();
						String terId = "";
						if(i<10){
							terId="0000000"+i;
						}else{
							terId="000000"+i;
						}
						tb_id.setMchtCd(merinfo.getId());//商户号
						tb_id.setTermId(terId); //终端号码
						tb.setId(tb_id);
						tb.setTmnlMoney(0);//押金
						tb.setBelong("1");
						tb.setBelongSub(String.valueOf(op.getOrgCode()));
						tb.setStatus("01");//初始状态
						tb.setDeviceCd("YJ");//默认sn号码
						tb.setRecCrtTs(new Date());//记录时间
						tb.setDialOut("60000");//终端呼出号码，默认暂定无用处
						tb.setTmnlMoneyIntype("1");//押金收取方式 0按照商户 1按照终端
						baseDao.editSave(tb);
						logger.info("-----添加商户终端信息成功-----商户号："+merinfo.getId()+"-----终端号："+tb.getId()+"-----");
						//终端风控信息
						TblEditTermRiskCfg ttr=merinfo.getTerminfoRisk();
						if(ttr!=null){//风控信息不为空
							for (int j = 0; j < 2; j++) { //借记卡01、贷记卡 00风控规则
								
								TblEditTermRiskCfgId  terRiskId=new TblEditTermRiskCfgId();
								if(j==0)//判断卡类型
										terRiskId.setCardType("00");
								else 
										terRiskId.setCardType("01");
								terRiskId.setMchtCd(merinfo.getId());//商户号
								terRiskId.setTermId(terId);//终端号
								TblEditTermRiskCfg terRisk=new TblEditTermRiskCfg();
								terRisk.setId(terRiskId);
								terRisk.setAccpetStartTime(ttr.getAccpetStartTime()); //营业开始时间
								terRisk.setAccpetEndTime(ttr.getAccpetEndTime()); //营业结束时间
								terRisk.setControlWay("1,2");//控制方式
								terRisk.setTotalPeriod("1");//周期
								terRisk.setRecCrtTs(new Date());//录入时间
								terRisk.setRecOprId("I");//插入操作标识符
								terRisk.setRecUpdOpr(String.valueOf(op.getId()));//操作员
								terRisk.setOperIn("I");//插入
								baseDao.editSave(terRisk);
								logger.info("-----添加商户终端风控信息成功-----商户号："+merinfo.getId()+"-----终端号："+terRisk.getId().getTermId()+"-----");
							}
						}else{
							throw new ServiceException(MerinfoReturninfo.S_7.getName());
						}
						i++;
					}
					logger.info("-----临时商户终端、终端风控信息添加成功-----商户号："+merinfo.getId()+"-----end");
				}else{
					throw new ServiceException(MerinfoReturninfo.S_2.getName());
				}
				//////结算账户信息
				TblEditMchtBankAccount  bankAccount= new TblEditMchtBankAccount();
				bankAccount=merinfo.getBankAccount();
				bankAccount.setOwnerCd(merinfo.getId());//商户号
				bankAccount.setAccountType("01"); //账户类型  **********************************
				bankAccount.setRecCrtTs(new Date());//记录时间
				bankAccount.setUcBccd(bankAccount.getBankCode().substring(0,3));//开户行选择
				bankAccount.setOperIn("I");
				bankAccount.setRecUpdOpr(String.valueOf(op.getId()));
				baseDao.editSave(bankAccount);
				logger.info("-----临时商户结算信息添加成功-----商户号："+merinfo.getId()+"-----end");
				//添加产品信息
				String[] productCode=merinfo.getProductCode();	//获取产品信息
				if(null!=productCode && productCode.length>0){
					List<TblEditMchtBizFee> feeList=merinfo.getFee();	//手续费 
					if(null==feeList || feeList.size()<1) 
					throw new  ServiceException(MerinfoReturninfo.S_4.getName());
					for(int j = 0; j < productCode.length; j++) {
						if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){		//银联扫码
							List<TblEditMchtBizDeal> unionpayBizDealList = getUnionpayMchtBizDealList(merinfo, op);
								if(unionpayBizDealList != null && unionpayBizDealList.size() > 0){
									for(TblEditMchtBizDeal ubizDeal : unionpayBizDealList){
										baseDao.editSave(ubizDeal);
										logger.info("-----添加商户银联扫码产品信息成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+ubizDeal.getProdCd()+"[transCd-->"+ubizDeal.getTransCd()+"]-----");
								}
							}	
						}else if (ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){		//支付宝微信
							List<TblEditMchtBizDeal> zwpayBizDealList = getZwpayMchtBizDealList(merinfo, op);
							if(zwpayBizDealList != null && zwpayBizDealList.size() > 0){
								for(TblEditMchtBizDeal zbizDeal : zwpayBizDealList){
									baseDao.editSave(zbizDeal);
									logger.info("-----添加商户支付宝微信产品信息成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+zbizDeal.getProdCd()+"[transCd-->"+zbizDeal.getTransCd()+"]-----");
								}
							}
						}else if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j])
								|| ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){	//直连T1/T0产品
							Map<String, String> dproMap=ConfigMerinfoUtil.getDirectProductList(productCode[j], false);
							List<TblEditMchtBizDeal> editMchtBizDealList = getDirectEditMchtBizDealList(dproMap, productCode[j], merinfo.getId(), String.valueOf(op.getId()));
							if(editMchtBizDealList != null && editMchtBizDealList.size()>0){
								for(TblEditMchtBizDeal editMchtBizDeals : editMchtBizDealList){
									baseDao.editSave(editMchtBizDeals);
									logger.info("-----添加商户直连T1/T0产品信息成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+editMchtBizDeals.getProdCd()+"[transCd-->"+editMchtBizDeals.getTransCd()+"]-----");
								}
							}
						}else{
							Map<String, String> proMap=ConfigMerinfoUtil.getPosFunction(productCode[j], false);		// 银行卡T1/T0产品
							List<TblEditMchtBizDeal> editMchtBizDealT = getEditMchtBizDealTList(proMap, merinfo.getId(), productCode[j], String.valueOf(op.getId()));
							if(editMchtBizDealT != null &&editMchtBizDealT.size() > 0){
								for(TblEditMchtBizDeal editMchtBizDealList : editMchtBizDealT){
										baseDao.editSave(editMchtBizDealList);
										logger.info("-----添加商户T1/T0产品信息成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+editMchtBizDealList.getProdCd()+"[transCd-->"+editMchtBizDealList.getTransCd()+"]-----");
								}
							}	
						}
						//添加手续费
						if(ConfigMerinfoUtil.T1_FUNCTION.equals(productCode[j]) || ConfigMerinfoUtil.T0_FUNCTION.equals(productCode[j])){ // 银行卡t1/t0
							List<TblEditMchtBizFee> editMchtBizFeeTList = getTblEditMchtBizFeeT(productCode[j], feeList, merinfo.getId(), op, true);
							if(editMchtBizFeeTList != null && editMchtBizFeeTList.size() > 0){
								for(TblEditMchtBizFee editMchtBizFeeT : editMchtBizFeeTList){
									baseDao.editSave(editMchtBizFeeT);
									logger.info("-----添加商户银行卡T1/T0产品手续费成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+editMchtBizFeeT.getProdCd()+"][SubBizCd-->"+editMchtBizFeeT.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFeeT.getMchtFeePercent()+"]-----");
								}
							}
						}else if (ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){	//银联扫码
							if(merinfo.getUpMccCd() != null && merinfo.getUpMccCd().length()>0){ //判断mcc是否选中
								TblEditMchtBizFee tempUionFee = feeList.get(5);
								List<TblEditMchtBizFee> tempUionFees = getUnionAndZwPayFeeList(tempUionFee, merinfo, op, productCode[j], true);
								if(tempUionFees != null && tempUionFees.size() > 0){
									for(TblEditMchtBizFee ubizFee : tempUionFees){
										baseDao.editSave(ubizFee);
										logger.info("-----添加商户银联扫码产品手续费成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+ubizFee.getProdCd()+"][SubBizCd-->"+ubizFee.getSubBizCd()+"[MchtFeePercent-->"+ubizFee.getMchtFeePercent()+"]-----");
									}
								}
							}
						}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){	//支付宝微信
							TblEditMchtBizFee tempzwFee = feeList.get(6);
							List<TblEditMchtBizFee> tempzwFees = getUnionAndZwPayFeeList(tempzwFee, merinfo, op, productCode[j], true);
							if(tempzwFees != null && tempzwFees.size() > 0){
								for(TblEditMchtBizFee zbizFee : tempzwFees){
									baseDao.editSave(zbizFee);
									logger.info("-----添加商户支付宝微信产品手续费成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+zbizFee.getProdCd()+"][SubBizCd-->"+zbizFee.getSubBizCd()+"[MchtFeePercent-->"+zbizFee.getMchtFeePercent()+"]-----");
								}
							}
						}else if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j]) ||
								ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){		//直连商户T1/T0手续费
							List<TblEditMchtBizFee> editMchtBizFeeList = getEditMchtBizFeeList(productCode[j], feeList, merinfo.getId(), String.valueOf(op.getId()), true);
							if(editMchtBizFeeList != null && editMchtBizFeeList.size() > 0){
								for(TblEditMchtBizFee editMchtBizFee : editMchtBizFeeList){
									baseDao.editSave(editMchtBizFee);
									logger.info("-----添加商户直连商户T1/T0手续费成功--商户号：["+merinfo.getId()+"]产品码[prodcd-->"+editMchtBizFee.getProdCd()+"][SubBizCd-->"+editMchtBizFee.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFee.getMchtFeePercent()+"]-----");
								}
							}
						}
					}
					logger.info("-----临时商户产品开通成功-----商户号："+merinfo.getId()+"-----end");
				}else{
					throw new ServiceException(MerinfoReturninfo.S_3.getName());
				}
				/////商户图片
				List<TblEditMchtPicture> pictrueList=merinfo.getPictrueList();
				if(null!=pictrueList && pictrueList.size()>=8){
					for (TblEditMchtPicture pi : pictrueList) {
						if(pi.getUrl()==null || pi.getUrl().equals("") || pi.getUrl().length()<1){
							continue;
						}
						TblEditMchtPicture pictrue=new TblEditMchtPicture();
						pictrue.setMchtCd(merinfo.getId());//商户号
						pictrue.setUrl(pi.getUrl().trim());//图片地址
						pictrue.setPindex(1);//顺序默认
						//String b=pi.getUrl().trim().substring(pi.getUrl().lastIndexOf("&")+1);
						//获取图片名称、pcode、fileid
						Random ra=new Random();
						int random=1000+ra.nextInt(8999);
						int first=pi.getUrl().trim().indexOf("mid=")+4;
						int sencond=pi.getUrl().trim().lastIndexOf("&");
						if(first>4 && sencond>0){
							pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
							pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
							pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
						}else{
							String b=pi.getUrl().trim().substring(pi.getUrl().lastIndexOf("&")+1);
							pictrue.setPcode("code");//拆封名称去掉后缀
							pictrue.setFileName(b);//名称
							pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
						}
						pictrue.setDocType("00");
						pictrue.setSystemflag("00");
						pictrue.setStatus("0");
						pictrue.setRecOprId("I");//插入操作
						pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
						pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
						baseDao.editSave(pictrue);
						logger.info("------添加商户图片信息成功-----商户号："+merinfo.getId()+"-----图片信息file_id:"+pictrue.getFileId()+"------");
					}
					logger.info("-----临时商户资料上传信息保存成功-----商户号："+merinfo.getId()+"-----end");
				}else{
					throw new ServiceException(MerinfoReturninfo.S_5.getName());
				}
				baseDao.editSave(merinfo);//商户信息
				logger.info("-----临时商户基本信息保存成功-----商户号："+merinfo.getId()+"-----");
				merchantDao.addSyslog(SysLogType.MERCHANT_ADD.getCode(),
								SysLogType.MERCHANT_ADD.getName(),
								op.getAccountNo(), 
								"操作员【" + op.getAccountNo()+ "】，添加商户【" + merinfo.getId() + "】成功");
				logger.info("-----特约商户申请成功-----商户号："+merinfo.getId()+"------------------------end");
				return MerinfoReturninfo.S_6.getName();
			} catch (DaoException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
				throw new ServiceException("添加商户信息出错");
			}

		}
		
		@Override
		public synchronized String saveMerinfo(TblEditMchtInf merchantInfo, Operators op) throws ServiceException {
			try {
				//商户基本信息
				TblEditMchtInf mergMerInfoSave = mergMerInfoToSave(merchantInfo, op);
				baseDao.editSave(mergMerInfoSave);
				logger.info("-----暂存商户基本信息成功-----商户号："+merchantInfo.getId()+"-----end");
				//受理市场扩展商户信息
				if("2".equals(op.getGroupCd())){
					TblEditMchtExtendInfo mchtExtendInfo = merchantInfo.getMchtExtendInfo();
					mchtExtendInfo.setId(merchantInfo.getId());
					baseDao.editSave(mchtExtendInfo);
					logger.info("-----暂存商户扩展信息成功-----商户号："+merchantInfo.getId()+"-----end");
				}
				//终端信息
				List<TblEditTermInf> terminList = merchantInfo.getTerminfoList();
				if(terminList != null && terminList.size() > 0){
					int i=1;
					for(TblEditTermInf tb:terminList){
						TblEditTermInfId tb_id=new TblEditTermInfId();
						String terId = "";
						if(i<10){
							terId="0000000"+i;
						}else{
							terId="000000"+i;
						}
						tb_id.setMchtCd(merchantInfo.getId());//商户号
						tb_id.setTermId(terId); //终端号码
						tb.setId(tb_id);
						tb.setTmnlMoney(0);//押金
						tb.setBelong("1");
						tb.setBelongSub(String.valueOf(op.getOrgCode()));
						tb.setStatus(MerinfoStatus.S_9.getCode());//暂存状态
						tb.setDeviceCd("YJ");//默认sn号码
						tb.setRecCrtTs(new Date());//记录时间
						tb.setDialOut("60000");//终端呼出号码，默认暂定无用处
						tb.setTmnlMoneyIntype("1");//押金收取方式 0按照商户 1按照终端
						baseDao.editSave(tb);
						logger.info("-----暂存商户终端信息成功-----商户号："+merchantInfo.getId()+"-----终端号："+tb.getId().getTermId()+"-----");
					//终端风控信息
					TblEditTermRiskCfg ttr = merchantInfo.getTerminfoRisk();
					if(ttr!=null){
						for (int j = 0; j < 2; j++) { //借记卡01、贷记卡 00风控规则
							
							TblEditTermRiskCfgId  terRiskId=new TblEditTermRiskCfgId();
							if(j==0)//判断卡类型
									terRiskId.setCardType("00");
							else 
									terRiskId.setCardType("01");
							terRiskId.setMchtCd(merchantInfo.getId());//商户号
							terRiskId.setTermId(terId);//终端号
							TblEditTermRiskCfg terRisk=new TblEditTermRiskCfg();
							terRisk.setId(terRiskId);
							terRisk.setAccpetStartTime(ttr.getAccpetStartTime()); //营业开始时间
							terRisk.setAccpetEndTime(ttr.getAccpetEndTime()); //营业结束时间
							terRisk.setControlWay("1,2");//控制方式
							terRisk.setTotalPeriod("1");//周期
							terRisk.setRecCrtTs(new Date());//录入时间
							terRisk.setRecOprId("I");//插入操作标识符
							terRisk.setRecUpdOpr(String.valueOf(op.getId()));//操作员
							terRisk.setOperIn("I");//插入
							baseDao.editSave(terRisk);
							logger.info("-----暂存商户终端风控信息成功-----商户号："+merchantInfo.getId()+"-----终端号："+tb.getId().getTermId()+"-----");
							}
						}
					i++;
					}
					logger.info("-----暂存商户终端、终端风控信息成功-----商户号："+merchantInfo.getId()+"-----end");
				}
				//结算账户信息
				TblEditMchtBankAccount  bankAccount = merchantInfo.getBankAccount();
				if(bankAccount != null){
					bankAccount.setOwnerCd(merchantInfo.getId());	//商户号
					bankAccount.setAccountType("01");	//账户类型
					bankAccount.setRecCrtTs(new Date());
					String bankCode = bankAccount.getBankCode();
					if(bankAccount.getBankName().length()<1){
						bankAccount.setBankName("0");
					}
					if(bankCode.length() > 0){
						bankAccount.setUcBccd(bankCode.substring(0, 3));	//开户行选择
					}else{
						bankAccount.setUcBccd("0");
						bankAccount.setBankCode("0");
					}
					if(bankAccount.getName().length()<1){
						bankAccount.setName("0");
					}
					if(bankAccount.getAccount().length()<1){
						bankAccount.setAccount("0");
					}
					bankAccount.setOperIn("I");
					bankAccount.setRecUpdOpr(String.valueOf(op.getId()));
					baseDao.editSave(bankAccount);
					logger.info("-----暂存商户结算账户信息成功-----商户号："+merchantInfo.getId()+"-----end");
				}
				//产品信息
				String[] productCode=merchantInfo.getProductCode();	//获取产品信息
				if(null!=productCode && productCode.length>0){
					List<TblEditMchtBizFee> feeList=merchantInfo.getFee();	//手续费 
					if(null==feeList || feeList.size()<1) 
					throw new  ServiceException(MerinfoReturninfo.S_4.getName());
					for(int j = 0; j < productCode.length; j++) {
						if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){		//银联扫码
							List<TblEditMchtBizDeal> unionpayBizDealList = getUnionpayMchtBizDealList(merchantInfo, op);
								if(unionpayBizDealList != null && unionpayBizDealList.size() > 0){
									for(TblEditMchtBizDeal ubizDeal : unionpayBizDealList){
										baseDao.editSave(ubizDeal);
										logger.info("-----暂存商户银联扫码产品信息成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+ubizDeal.getProdCd()+"[transCd-->"+ubizDeal.getTransCd()+"]-----");
								}
							}	
						}else if (ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){		//支付宝微信
							List<TblEditMchtBizDeal> zwpayBizDealList = getZwpayMchtBizDealList(merchantInfo, op);
							if(zwpayBizDealList != null && zwpayBizDealList.size() > 0){
								for(TblEditMchtBizDeal zbizDeal : zwpayBizDealList){
									baseDao.editSave(zbizDeal);
									logger.info("-----暂存商户支付宝微信产品信息成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+zbizDeal.getProdCd()+"[transCd-->"+zbizDeal.getTransCd()+"]-----");
								}
							}
						}else if(Constant.STR_NUMBER_ONE.equals(merchantInfo.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j])
								|| ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){	//直连T1/T0产品
							Map<String, String> dproMap=ConfigMerinfoUtil.getDirectProductList(productCode[j], false);
							List<TblEditMchtBizDeal> editMchtBizDealList = getDirectEditMchtBizDealList(dproMap, productCode[j], merchantInfo.getId(), String.valueOf(op.getId()));
							if(editMchtBizDealList != null && editMchtBizDealList.size()>0){
								for(TblEditMchtBizDeal editMchtBizDeals : editMchtBizDealList){
									baseDao.editSave(editMchtBizDeals);
									logger.info("-----暂存商户直连T1/T0产品信息成功--商户号：["+merchantInfo.getId()+"]产品码[prodcd-->"+editMchtBizDeals.getProdCd()+"[transCd-->"+editMchtBizDeals.getTransCd()+"]-----");
								}
							}
						}else{
							Map<String, String> proMap=ConfigMerinfoUtil.getPosFunction(productCode[j], false);		// 银行卡T1/T0产品
							List<TblEditMchtBizDeal> editMchtBizDealT = getEditMchtBizDealTList(proMap, merchantInfo.getId(), productCode[j], String.valueOf(op.getId()));
							if(editMchtBizDealT != null &&editMchtBizDealT.size() > 0){
								for(TblEditMchtBizDeal editMchtBizDealList : editMchtBizDealT){
										baseDao.editSave(editMchtBizDealList);
										logger.info("-----暂存商户T1/T0产品信息成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+editMchtBizDealList.getProdCd()+"[transCd-->"+editMchtBizDealList.getTransCd()+"]-----");
								}
							}	
						}
						//添加手续费
						if(ConfigMerinfoUtil.T1_FUNCTION.equals(productCode[j]) || ConfigMerinfoUtil.T0_FUNCTION.equals(productCode[j])){ // 银行卡t1/t0
							List<TblEditMchtBizFee> editMchtBizFeeTList = getTblEditMchtBizFeeT(productCode[j], feeList, merchantInfo.getId(), op, false);
							if(editMchtBizFeeTList != null && editMchtBizFeeTList.size() > 0){
								for(TblEditMchtBizFee editMchtBizFeeT : editMchtBizFeeTList){
									baseDao.editSave(editMchtBizFeeT);
									logger.info("-----暂存商户银行卡T1/T0产品手续费成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+editMchtBizFeeT.getProdCd()+"][SubBizCd-->"+editMchtBizFeeT.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFeeT.getMchtFeePercent()+"]-----");
								}
							}
						}else if (ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){	//银联扫码
							if(merchantInfo.getUpMccCd() != null && merchantInfo.getUpMccCd().length()>0){ //判断mcc是否选中
								TblEditMchtBizFee tempUionFee = feeList.get(5);
								List<TblEditMchtBizFee> tempUionFees = getUnionAndZwPayFeeList(tempUionFee, merchantInfo, op, productCode[j], false);
								if(tempUionFees != null && tempUionFees.size() > 0){
									for(TblEditMchtBizFee ubizFee : tempUionFees){
										baseDao.editSave(ubizFee);
										logger.info("-----暂存商户银联扫码产品手续费成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+ubizFee.getProdCd()+"][SubBizCd-->"+ubizFee.getSubBizCd()+"[MchtFeePercent-->"+ubizFee.getMchtFeePercent()+"]-----");
									}
								}
							}
						}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){	//支付宝微信
							TblEditMchtBizFee tempzwFee = feeList.get(6);
							List<TblEditMchtBizFee> tempzwFees = getUnionAndZwPayFeeList(tempzwFee, merchantInfo, op, productCode[j], false);
							if(tempzwFees != null && tempzwFees.size() > 0){
								for(TblEditMchtBizFee zbizFee : tempzwFees){
									baseDao.editSave(zbizFee);
									logger.info("-----暂存商户支付宝微信产品手续费成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+zbizFee.getProdCd()+"][SubBizCd-->"+zbizFee.getSubBizCd()+"[MchtFeePercent-->"+zbizFee.getMchtFeePercent()+"]-----");
								}
							}
						}else if(Constant.STR_NUMBER_ONE.equals(merchantInfo.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j]) ||
								ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){		//直连商户T1/T0手续费
							List<TblEditMchtBizFee> editMchtBizFeeList = getEditMchtBizFeeList(productCode[j], feeList, merchantInfo.getId(), String.valueOf(op.getId()), false);
							if(editMchtBizFeeList != null && editMchtBizFeeList.size() > 0){
								for(TblEditMchtBizFee editMchtBizFee : editMchtBizFeeList){
									baseDao.editSave(editMchtBizFee);
									logger.info("-----暂存商户直连商户T1/T0手续费成功--商户号：["+merchantInfo.getId()+"]产品码：[prodcd-->"+editMchtBizFee.getProdCd()+"][SubBizCd-->"+editMchtBizFee.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFee.getMchtFeePercent()+"]-----");
								}
							}
						}
					}
					logger.info("-----暂存商户产品开通信息成功-----商户号："+merchantInfo.getId()+"-----end");
				}
				//商户图片
				List<TblEditMchtPicture> pictrueList = merchantInfo.getPictrueList();
				if(pictrueList != null){
					List<TblEditMchtPicture> mergPictrueList = mergPictrueListToSave(merchantInfo, op, false);
					for(TblEditMchtPicture pictrue : mergPictrueList){
						baseDao.editSave(pictrue);
						logger.info("----暂存商户图片资料信息成功--商户号：["+merchantInfo.getId()+"]图片信息[file_id-->"+pictrue.getFileId()+"]-----");
					}
					logger.info("----暂存商户图片资料信息成功-----商户号：["+merchantInfo.getId()+"]-----end");
				}
				logger.info("-----暂存商户信息成功----------商户号："+merchantInfo.getId()+"-------------------------------end");
				return MerinfoReturninfo.S_45.getName();
			} catch (DaoException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
				throw new ServiceException("进件暂存商户信息出错！");
			}
		}
		
	/**
	 * 审核查询商户信息
	 * @param merinfoNo 临时商户号
	 * @param showName 是否根据code显示名称
	 * @return TblEditMchtInf  商户信息
	 * @author zbl    v1.0
	 * @author pc  后期改造可细化每个查询语句需要的字段、改用SQL 查询
	 * */
	 
	@Transactional(readOnly=true)
	public TblEditMchtInf queryMerinfoTmpInfo(String mer_infoNo,boolean showName,boolean isRebut,boolean isOpName) throws ServiceException {
		 TblEditMchtInf mer_info=null;
		
		 Object[] param={mer_infoNo};
		 try {
			if(null==mer_infoNo) return mer_info; //为空返回
			
			//商户信息
			String mer_hql=" from TblEditMchtInf t where t.id=?";
			mer_info=(TblEditMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
			if(showName){//根据code显示名称
				mer_info.setCertifType(ConfigMerinfoUtil.getCertifType(mer_info.getCertifType()));//证件类型
				if(null==mer_info.getProvCd() || mer_info.getProvCd().trim().length()<5)mer_info.setProvCd("310000");
				if(null==mer_info.getCityCd() || mer_info.getCityCd().trim().length()<5)mer_info.setCityCd("310100");
				if(null==mer_info.getAreaCd() || mer_info.getAreaCd().trim().length()<5)mer_info.setAreaCd("310104");
				mer_info.setProvCd(ConfigMerinfoUtil.getGBProviceName(mer_info.getProvCd()));//省份
				mer_info.setCityCd(ConfigMerinfoUtil.getGBCityName(mer_info.getCityCd()));//城市
				mer_info.setAreaCd(ConfigMerinfoUtil.getGBAreaName(mer_info.getAreaCd()));//地区
				
			}
			if(isOpName){
				//查询进件人员(后期可放入与商户联查，提高页面响应速度)
				String q_sql="SELECT T.REAL_NAME FROM T_OPERATORS T WHERE T.ID=?";
				Object[] params_1={mer_info.getRecUpdOpr()};
				Object op_name=pageDao.findObj(q_sql, params_1);
				mer_info.setRecUpdOpr(String.valueOf(op_name));
			}
			//终端信息
			String ter_hql="from TblEditTermInf t where t.id.MchtCd=?";
			List<?> objList_ter=pageDao.queryAll(ter_hql, param);
			if(null!=objList_ter && objList_ter.size()>0){
				List<TblEditTermInf> terList=new ArrayList<TblEditTermInf>();
				for (Object object : objList_ter) {
					TblEditTermInf terminfo=(TblEditTermInf)object;
					if(showName){
						terminfo.setTermTp(ConfigMerinfoUtil.getPosType(terminfo.getTermTp()));//获取终端类型具体名称
					}
					//查询终端风控信息
					String risk_hql="from TblEditTermRiskCfg t where t.id.MchtCd=? and t.id.TermId=?";
					 Object[] param_risk={mer_infoNo,terminfo.getId().getTermId()};
					List<?> objList_risk=pageDao.queryAll(risk_hql, param_risk);
					if(null!=objList_risk && objList_risk.size()>0){
						List<TblEditTermRiskCfg> riskList=new ArrayList<TblEditTermRiskCfg>();
						for (Object risk : objList_risk) {
							TblEditTermRiskCfg fee=(TblEditTermRiskCfg)risk;
							riskList.add(fee);
						}
						terminfo.setRiskCfgList(riskList); //set 终端风控信息
					}
					terList.add(terminfo);
				}
				mer_info.setTerminfoList(terList);//set终端
				TblEditTermRiskCfg  tmpTb= new TblEditTermRiskCfg();
				tmpTb.setAccpetStartTime(terList.get(0).getRiskCfgList().get(0).getAccpetStartTime());
				tmpTb.setAccpetEndTime(terList.get(0).getRiskCfgList().get(0).getAccpetEndTime());
				mer_info.setTerminfoRisk(tmpTb);//获取营业时间
			}
			//产品信息
			String del_hql="select t.prodCd,t.transCd from  TblEditMchtBizDeal t where t.mchtCd=?";
			List<?> objList_del=pageDao.queryAll(del_hql, param);
			if(null!=objList_del && objList_del.size()>0){
				List<TblEditMchtBizDeal> delList=new ArrayList<TblEditMchtBizDeal>();
				String[] produdctArrayStr=new String[objList_del.size()];
				int i=0;
				Iterator<?> iter=objList_del.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblEditMchtBizDeal terminfo=new TblEditMchtBizDeal();
					terminfo.setProdCd(String.valueOf(obj[0]));
					terminfo.setTransCd(String.valueOf(obj[1]));
					delList.add(terminfo);
						produdctArrayStr[i]=terminfo.getTransCd();
					i++;
				}
				 
				mer_info.setBizDelList(delList); //产品集合
				mer_info.setProductStrs(produdctArrayStr);//产品
				
				String[] productCodeStr=queryMchtBizDealArray(mer_infoNo, false,showName);
				mer_info.setProductCode(productCodeStr); //保存当前商户所选择的业务模式 
			}
			
			
			//结算信息
			String settle_hql="from TblEditMchtBankAccount t where t.ownerCd=?";
			TblEditMchtBankAccount bankAccount=(TblEditMchtBankAccount)baseDao.createQueryUniqueResult(settle_hql,param );
			mer_info.setBankAccount(bankAccount);//SET 结算信息
			
			//手续费
			String fees_hql = "";
			String[] productCodeFlag=queryMchtBizDealArray(mer_infoNo, false, false);
			if(Constant.STR_NUMBER_ONE.equals(mer_info.getGroupCD()) && 
					(Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
					Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){
				fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax,mchtAFeePercent from TblEditMchtBizFee t where t.mchtCd=? order by prodCd desc ";
			}else{
				fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax,mchtAFeePercent from TblEditMchtBizFee t where t.mchtCd=? ";
			}
			List<?> objList_fee=pageDao.queryAll(fees_hql, param);
			if(Constant.STR_NUMBER_ONE.equals(mer_info.getGroupCD()) && 
					(Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
					Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){	//直联商户
				List<TblEditMchtBizFee> dfeeList = getMerinfoEditMchtBizFeeList(objList_fee, mer_info, showName);
				mer_info.setFee(dfeeList);
			}else{
				if(null!=objList_fee && objList_fee.size()>0){
					List<TblEditMchtBizFee> feeList=new ArrayList<TblEditMchtBizFee>();
					Iterator<?> iter=objList_fee.iterator();
					int i=0;
					while(iter.hasNext()){
						Object[] obj=(Object[])iter.next();
						if(!(ConfigMerinfoUtil.ZPAY_FUNCTION_Z.equals(obj[1]) || ConfigMerinfoUtil.WPAY_FUNCTION_Z.equals(obj[1]) 
								|| ConfigMerinfoUtil.WPAY_FUNCTION_F.equals(obj[1]) || "1691".equals(obj[1]))){
							if(obj[3].equals(ConfigMerinfoUtil.T0_2005_FUNCTION) || 
									   obj[3].equals(ConfigMerinfoUtil.T0_2004_FUNCTION)){//t0 划付手续费  跳过
										continue;
								}
									if(String.valueOf(obj[3]).equals("0002000") && i==0){//只有t0
										feeList.add(null);
										feeList.add(null);
									}
									TblEditMchtBizFee fee=new TblEditMchtBizFee();
									fee.setMchtCd(String.valueOf(obj[0]));
									fee.setProdCd(String.valueOf(obj[1]));
									fee.setBizCd(String.valueOf(obj[2]));
									fee.setSubBizCd(String.valueOf(obj[3]));
									if(null != obj[4] && !(obj[4].toString().trim().equals(""))){
										fee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
									}
									if(null == obj[5] || obj[5].toString().trim().equals("")){ 
										fee.setMchtFeePctMax(0d);
									}else{
										fee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
									}
									if(showName){
										String name="";
										if(fee.getProdCd().equals(ConfigMerinfoUtil.T1_FUNCTION)){
											name="T1";
										}else if(fee.getProdCd().equals(ConfigMerinfoUtil.T0_FUNCTION)){
											name="T0";
										}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(fee.getProdCd())){
											name = "银联";
										}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(fee.getProdCd())){
											name = "支付宝微信";
										}
										String feeCodeName = ConfigMerinfoUtil.getFeeList(String.valueOf(obj[3])); //根据code 显示手续费名称
										fee.setMchtFeeMd(name + (feeCodeName == null ? "" : feeCodeName));
									}
									if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(String.valueOf(obj[3])) &&
											null != obj[6] && !(obj[6].toString().trim().equals(""))){
										fee.setMchtAFeePercent(Double.parseDouble(String.valueOf((obj[6]))));
									}
									feeList.add(fee); 
									i++;
						}
					}
					mer_info.setFee(feeList); //set手续费集合
				}
			}
			//图片信息
			String pic_hql="select t.Url,t.DocType  from TblEditMchtPicture t where t.MchtCd=? order by t.Pcode ASC ";
			List<?> objList_pic=pageDao.queryAll(pic_hql, param);
			if(null!=objList_pic && objList_pic.size()>0){
				List<TblEditMchtPicture> picList=new LinkedList<TblEditMchtPicture>();
				Iterator<?> iter=objList_pic.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblEditMchtPicture picture=new TblEditMchtPicture();
					String url=String.valueOf(obj[0]);
					//url=url.substring(url.lastIndexOf("/")+1);
					picture.setUrl(url);
					picList.add(picture); 
				}
				mer_info.setPictrueList(picList);//图片路径地址
			}
			//查询驳回原因
			if(isRebut){
				String audit_hql="from AuditingItem  a where a.audit_code=? and a.obj_Audited=? and a.result_code=?";
				Object[] params_2={AuditingType.MERCHANT_LAST_AUDITING.getCode(),mer_infoNo,AuditingResultCodeType.REFUSE.getCode()};
				List<?> objList_audit=pageDao.queryAll(audit_hql, params_2);
				if(null!=objList_audit && objList_audit.size()>0){
					List<AuditingItem> aiList=new ArrayList<AuditingItem>();
					for (Object obj : objList_audit) {
						AuditingItem ai=(AuditingItem)obj;
						aiList.add(ai);
					}
					mer_info.setAuditList(aiList);//驳回原因
				}
			}
			//商户扩展信息
			String extend_hql="from TblEditMchtExtendInfo t where t.id=?";
			TblEditMchtExtendInfo tblEditMchtExtendInfo = (TblEditMchtExtendInfo)baseDao.createQueryUniqueResult(extend_hql,param );
			if(tblEditMchtExtendInfo!=null){
				if(StringUtils.isNotEmpty(tblEditMchtExtendInfo.getDevelopPerson())){
					String operator_hql="from Operators t where t.id=?";
					Object[] paramR={Long.parseLong(tblEditMchtExtendInfo.getDevelopPerson())};
					Operators operators = (Operators)baseDao.createQueryUniqueResult(operator_hql,paramR);
					if(operators != null){
						tblEditMchtExtendInfo.setDevelopPersonName(operators.getRealName());
					}
				}
			}
			mer_info.setMchtExtendInfo(tblEditMchtExtendInfo);
			return  mer_info;
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException(e.getMessage(),e);
		}
	}
	
  	@Override
	public TblMchtInf queryMerchat(String merchtNo) throws ServiceException {
		String sql = "SELECT e.MCHT_CD,e.NAME_BUSI,e.STATUS,e.CONTACT_NAME,e.CONTACT_PHONENO,e.Name FROM tbl_mcht_inf e  where e.MCHT_CD = ?";
		TblMchtInf esmidinfo = new TblMchtInf();
		try {
			Object[] param={merchtNo};
			Object[] obj = (Object[]) pageDao.findObj(sql,param);
			if (obj != null) {
				esmidinfo.setId(String.valueOf(obj[0]));
				esmidinfo.setNameBusi(obj[1].toString());
				esmidinfo.setStatus(MerchantStatus.valueOfCode(
						Integer.valueOf(obj[2].toString())).getName());
				esmidinfo.setContactName(obj[3].toString());
				esmidinfo.setContactPhoneNo(obj[4].toString());
				esmidinfo.setName(obj[5].toString());
				//esmidinfo.setTerNums(Constance.Null2EmptyTrim(obj[5]));
			}
		} catch (DaoException e) {
			logger.error("查询商户基本信息失败", e);
			throw new ServiceException("查询商户基本信息失败");
		}
		return esmidinfo;
	}
	/**
	 * 审核商户信息
	 * @param op 操作员
	 * @return TblEditMchtInf  商户信息
	 * @author zbl   
	 * @throws  
	 * */
	@Transactional(rollbackFor = { ServiceException.class })
	public synchronized String checkMerinfo(Operators op, TblEditMchtInf newMerinfo) throws ServiceException {
		try {
			if(null == newMerinfo || null==newMerinfo.getId() || newMerinfo.getId().trim().length()!=15) return MerinfoReturninfo.S_10.getName();
			if(null==newMerinfo.getUcBccd() || newMerinfo.getUcBccd().length()<5 || newMerinfo.getUcBccd().substring(4).equals("null")) return MerinfoReturninfo.S_17.getName();
			if(null==newMerinfo.getUpMccCd()) return MerinfoReturninfo.S_28.getName();
			if(null==newMerinfo.getAudit()  || null==newMerinfo.getAudit().getResult_code() )   return MerinfoReturninfo.S_18.getName();
			
			//领件状态更新
			String r_sql="UPDATE T_RECEIVE T SET T.STATUS='1',T.RESERVE1=SYSDATE WHERE T.STATUS='0' AND  T.MERNO=?";
			List<Object> receiveList=new ArrayList<Object>();
			receiveList.add(newMerinfo.getId());
			int r_count=sqlBaseDao.deleteBySql(r_sql, receiveList);
			if(r_count<1){ 
				logger.info("----更新商户["+newMerinfo.getId()+"]领件状态为已处理失败-----");
				throw new ServiceException(MerinfoReturninfo.S_19.getName());
			}
			logger.info("------商户["+newMerinfo.getId()+"]领件状态更新成功----"); 
			
			//添加审核信息
			AuditingItem  audit= newMerinfo.getAudit();
			audit.setAudit_code(AuditingType.MERCHANT_LAST_AUDITING.getCode());//获取审核编码
			audit.setAudit_name(AuditingType.MERCHANT_LAST_AUDITING.getName());//获取审核名称
			audit.setObj_Audited(newMerinfo.getId());//审核对象
			audit.setOperators(op.getAccountNo());//操作员账号
			
			//查询进件前商户信息
			TblEditMchtInf  m_info=queryMerinfoTmpInfo(newMerinfo.getId(),false,false,false);
			
			if(null==m_info)throw new ServiceException(MerinfoReturninfo.S_29.getName()); //查询为空
			
			if(audit.getResult_code().equals(AuditingResultCodeType.REFUSE.getCode())){//主动驳回
				m_info.setStatus(MerinfoStatus.S_4.getCode());//审核驳回
				baseDao.editUpdate(m_info);
				logger.info("------商户["+newMerinfo.getId()+"]审核被驳回，更新状态为["+MerinfoStatus.S_4.getCode()+"]成功----"); 
				baseDao.editSave(audit);//添加审核意见
				return MerinfoReturninfo.S_20.getName();
			}
			
			String validateStr=validateCount(m_info,op);//判断次数
			if(null!=validateStr) {
				audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
				audit.setResult_detail(validateStr);
				baseDao.editSave(audit);//添加审核意见
				m_info.setStatus(MerinfoStatus.S_4.getCode()); //驳回
				baseDao.editUpdate(m_info);//更新
				return validateStr;
			}
			
			String validate=validateExist(m_info,op);//校验 身份证，银行卡，营业执照，非法人身份证是否被风控
			if(null!=validate){
				audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
				audit.setResult_detail(validate);
				baseDao.editSave(audit);//添加审核意见
				m_info.setStatus(MerinfoStatus.S_4.getCode()); //驳回
				baseDao.editUpdate(m_info);//更新
				return validate;
			}
			/*if("01".equals(m_info.getCertifType())){	//验证法人身份证信息合法性
				boolean validatecIdCard = validateIdInfo(m_info.getCertif(), m_info.getCertifNo(), "1");
				if(!validatecIdCard){	
					audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
					audit.setResult_detail("法人身份证号码信息无效");
					baseDao.editSave(audit);//添加审核意见
					m_info.setStatus(MerinfoStatus.S_4.getCode()); //驳回
					baseDao.editUpdate(m_info);//更新
					return "法人身份证号码信息无效";
				}
			}
			if(m_info.getStlmWayDesc() != null && m_info.getStlmWayDesc().length()>0){ //验证非法人身份证信息合法性
				boolean validatesIdCard = validateIdInfo(m_info.getBankAccount().getName(), m_info.getStlmWayDesc(), "2");
				if(!validatesIdCard){
					audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
					audit.setResult_detail("非法人身份证号码信息无效");
					baseDao.editSave(audit);//添加审核意见
					m_info.setStatus(MerinfoStatus.S_4.getCode()); //驳回
					baseDao.editUpdate(m_info);//更新
					return "非法人身份证号码信息无效";
				}
			}
			
			//验证结算账户信息
			boolean validatejIdCard = validateIdInfo(m_info.getBankAccount().getName(), m_info.getBankAccount().getAccount(), "3");
			if(!validatejIdCard){
				audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
				audit.setResult_detail("结算卡号信息无效");
				baseDao.editSave(audit);//添加审核意见
				m_info.setStatus(MerinfoStatus.S_4.getCode()); //驳回
				baseDao.editUpdate(m_info);//更新
				return "结算卡号信息无效";
			}*/
			
			if(null!=m_info.getStatus() && m_info.getStatus().equals(MerinfoStatus.S_0.getCode())){//已经审核通过
				String sql="DELETE FROM T_RECEIVE T WHERE T.MERNO=? AND T.STATUS='0'";
				List<Object> receiveList1=new ArrayList<Object>();
				receiveList1.add(newMerinfo.getId());
				sqlBaseDao.deleteBySql(sql, receiveList1);
				return MerinfoReturninfo.S_30.getName();
			}
			String countSql ="SELECT count(1) FROM tbl_mcht_inf t WHERE t.busi_rang=? ";
			Object[] params={newMerinfo.getId()};
			Object obj=pageDao.findObj(countSql,params );
			if(null!=obj ){
				if(Long.parseLong(obj.toString())>1){ 
					return MerinfoReturninfo.S_30.getName();
				}
				
			}
			baseDao.editSave(audit);//添加审核意见
			logger.info("------商户["+newMerinfo.getId()+"]审核意见添加成功----");
			
			//更新原表商户状态
			String u_sql="UPDATE TBL_EDIT_MCHT_INF T  SET T.STATUS='"+MerinfoStatus.S_0.getCode()+"' WHERE T.MCHT_CD=?";
			List<Object> objParamsList=new ArrayList<Object>();
			objParamsList.add(newMerinfo.getId());
			int u_count=sqlBaseDao.deleteBySql(u_sql, objParamsList);
			if(u_count!=1)   throw new ServiceException(MerinfoReturninfo.S_21.getName());
			logger.info("------商户["+newMerinfo.getId()+"]审核通过，更新状态为["+MerinfoStatus.S_0.getCode()+"]成功----");
			 
			String serial=merchantDao.handleMerchantno("850", newMerinfo.getUcBccd().substring(4), newMerinfo.getUpMccCd());
			String merinfoNo="850"+newMerinfo.getUcBccd().substring(4)+newMerinfo.getUpMccCd()+serial;
			logger.info("------开始插入正式表：临时商户号："+newMerinfo.getId()+"---->正式商户号："+merinfoNo);
			
			//商户扩展信息
			String extend_hql="from TblEditMchtExtendInfo t where t.id=?";
			Object[] param = {newMerinfo.getId()};
			TblEditMchtExtendInfo tblEditMchtExtendInfo = (TblEditMchtExtendInfo)baseDao.createQueryUniqueResult(extend_hql,param );
			if(tblEditMchtExtendInfo!=null){
				TblMchtExtendInfo tblMchtExtendInfo = new TblMchtExtendInfo();
				tblMchtExtendInfo.setId(merinfoNo);
				tblMchtExtendInfo.setDevelopPerson(tblEditMchtExtendInfo.getDevelopPerson());
				tblMchtExtendInfo.setBusiLiceStartDate(tblEditMchtExtendInfo.getBusiLiceStartDate());
				tblMchtExtendInfo.setBusiLiceEndDate(tblEditMchtExtendInfo.getBusiLiceEndDate());
				tblMchtExtendInfo.setTermProperty(tblEditMchtExtendInfo.getTermProperty());
				tblMchtExtendInfo.setCertifStartDate(tblEditMchtExtendInfo.getCertifStartDate());
				tblMchtExtendInfo.setCertifEndDate(tblEditMchtExtendInfo.getCertifEndDate());
				tblMchtExtendInfo.setBackup5(tblEditMchtExtendInfo.getBackup5());
				baseDao.editSave(tblMchtExtendInfo);
			}
			
			if(merinfoNo.length()!=15){
				logger.info("当前mcc["+newMerinfo.getUpMccCd()+"]| 32code["+newMerinfo.getUcBccd()+"]  ");
				throw new ServiceException(MerinfoReturninfo.S_1.getName());
			}
			 Date currentDate=new Date();
			 TblMchtInf merinfo=new TblMchtInf();
			 merinfo.setId(merinfoNo);
			 merinfo.setBusiRang(newMerinfo.getId());/////保存临时表的商户号
			 merinfo.setSn(serial);
			 merinfo.setAipBranCd(m_info.getAipBranCd());
			 merinfo.setOriChnl(m_info.getOriChnl());
			 merinfo.setBankBelongCd(m_info.getBankBelongCd());
			 String applDate = DateUtil.getDate(new Date(), 0, "yyyy-MM-dd");
			 merinfo.setApplDate(applDate);//应用时间 
			 merinfo.setApprDate(m_info.getRecCrtTs());//进件时间
			 merinfo.setName(m_info.getName());
			 merinfo.setNameBusi(m_info.getNameBusi());
			 merinfo.setBusiLiceNo(m_info.getBusiLiceNo());
			 merinfo.setBusiMain(m_info.getBusiMain());
			 merinfo.setCertif(m_info.getCertif());
			 merinfo.setCertifType(m_info.getCertifType());
			 merinfo.setCertifNo(m_info.getCertifNo());
			 merinfo.setNationCd(m_info.getNationCd().trim());//商户类型
			 merinfo.setProvCd(m_info.getProvCd());
			 merinfo.setCityCd(m_info.getCityCd());
			 merinfo.setAreaCd(m_info.getAreaCd());
			 merinfo.setRegAddr(m_info.getRegAddr());
			 merinfo.setContactName(m_info.getContactName());
			 merinfo.setContactPhoneNo(m_info.getContactPhoneNo());
			 merinfo.setIsGroup(m_info.getIsGroup());//商户等级
			 merinfo.setMoneyToGroup(m_info.getMoneyToGroup());
			 merinfo.setStlmWay(m_info.getStlmWay());
			 merinfo.setStlmInsCircle(m_info.getStlmInsCircle());
			 merinfo.setStatus(MerinfoStatus.S_0.getCode());//正常状态
			 merinfo.setIsUpStandard(m_info.getIsUpStandard());
			 merinfo.setApprovalUserName(m_info.getApprovalUserName());//账户对公或对私
			 merinfo.setBillingType(m_info.getBillingType());
			 merinfo.setExt1(m_info.getExt1());
			 merinfo.setExt2(m_info.getExt2());
			 merinfo.setExt3(m_info.getExt3());
			 merinfo.setExt4(m_info.getExt4());
			 merinfo.setRecCrtTs(currentDate);
			 merinfo.setOperIn("I");
			 merinfo.setRecUpdOpr(m_info.getRecUpdOpr());//进件人员
			 merinfo.setOriChnlDesc(String.valueOf(op.getId()));//保存审核人员id
			 merinfo.setMcc(m_info.getUpMccCd());
			 merinfo.setUpMccCd(m_info.getUpMccCd());//mcc
			 merinfo.setUcBccd(m_info.getUcBccd());//32域
			 merinfo.setDvpBy(m_info.getDvpBy()); //商户结算类型
			 merinfo.setStlmWayDesc(m_info.getStlmWayDesc());//非法人身份证号
			 merinfo.setGroupCD(m_info.getGroupCD());//商户直间连选择
			 merinfo.setUcBccdArea(m_info.getUcBccdArea());//商户机构
			  
			 /*merinfo.setMcc(newMerinfo.getUpMccCd());//mcc
			 merinfo.setUpMccCd(newMerinfo.getUpMccCd());//mcc
			 merinfo.setUcBccd(op.getOrgCode().substring(0, 4)+newMerinfo.getUcBccd());//32域*/			 
			 baseDao.editSave(merinfo);
			 logger.info("---正式商户表添加["+merinfoNo+"]成功---");
			 
			////终端信息
			List<TblEditTermInf> terminList=m_info.getTerminfoList();
			if(null!=terminList && terminList.size()>0){
				for (TblEditTermInf tb:terminList) {
					String sql="SELECT SEQ_DEVICE_CD.nextval CURRENTS FROM dual ";
					Object currentSeq=sqlBaseDao.findObj(sql, null);
					TblTermInf  terminfo=new TblTermInf();
					TblTermInfId terminfoId=new TblTermInfId();
					terminfoId.setMchtCd(merinfoNo);
					terminfoId.setTermId(tb.getId().getTermId());
					terminfo.setId(terminfoId);
					terminfo.setStatus(tb.getStatus());//初始状态
					terminfo.setTermTp(tb.getTermTp());
					terminfo.setBelong(tb.getBelong());
					terminfo.setBelongSub(tb.getBelongSub());
					terminfo.setTmnlMoneyIntype(tb.getTmnlMoneyIntype());
					terminfo.setTmnlMoney(tb.getTmnlMoney());
					terminfo.setInstalllocation(tb.getInstalllocation());
					terminfo.setTmnlIntype(tb.getTmnlIntype());
					terminfo.setDeviceCd("YJ"+String.valueOf(currentSeq));//终端序列号
					terminfo.setRecOprId("I");
					terminfo.setRecCrtTs(currentDate);//记录时间
					terminfo.setRecUpdOpr(String.valueOf(op.getId()));
					terminfo.setDialOut(tb.getDialOut());//终端呼出号码，默认暂定无用处
					baseDao.editSave(terminfo);
					logger.info("---正式终端表添加商户["+merinfoNo+"]的终端["+tb.getId().getTermId()+"]成功---");
				}
			}
			//终端风控信息
			if(newMerinfo.getTerminfoList()!=null){
				for (int i = 0; i < newMerinfo.getTerminfoList().size(); i++) {
					for (int j = 0; j < newMerinfo.getTerminfoList().get(i).getRiskCfgList().size(); j++) {
						TblEditTermRiskCfg  tmpRisk=newMerinfo.getTerminfoList().get(i).getRiskCfgList().get(j);
						TblTermRiskCfg risk= new TblTermRiskCfg();
						TblTermRiskCfgId riskId=new TblTermRiskCfgId();
						riskId.setMchtCd( merinfoNo);//商户号
						riskId.setTermId(tmpRisk.getId().getTermId());
						riskId.setCardType(tmpRisk.getId().getCardType());
						risk.setId(riskId);
						risk.setTotalLimitmoney(tmpRisk.getTotalLimitmoney());
						risk.setAccpetStartTime(tmpRisk.getAccpetStartTime());
						risk.setAccpetEndTime(tmpRisk.getAccpetEndTime());
						risk.setSingleLimitmoney(tmpRisk.getSingleLimitmoney());
						risk.setSingleMinMoney(tmpRisk.getSingleMinMoney());
						risk.setControlWay("1,2");//控制方式
						risk.setTotalPeriod("1");//周期
						risk.setRecCrtTs(currentDate);
						risk.setRecOprId("I");
						risk.setOperIn("I");
						risk.setRecUpdOpr(String.valueOf(op.getId()));
						baseDao.editSave(risk);
						logger.info("-----正式风控表添加商户["+merinfoNo+"]的终端["+tmpRisk.getId().getTermId()+"]的卡["+riskId.getCardType()+"]风控信息成功-----");
					}
				}
			}
			//////结算账户信息
			TblEditMchtBankAccount  bankAccountTmp= m_info.getBankAccount();
			TblMchtBankAccount bankAccount=new TblMchtBankAccount();
			bankAccount.setOwnerCd(merinfoNo);//商户号
			bankAccount.setAccountType(bankAccountTmp.getAccountType()); //账户类型  **********************************
			bankAccount.setRecCrtTs(bankAccountTmp.getRecCrtTs());//记录时间
			bankAccount.setUcBccd(bankAccountTmp.getUcBccd());//开户行选择
			bankAccount.setBankCode(bankAccountTmp.getBankCode());
			bankAccount.setBankName(bankAccountTmp.getBankName());
			bankAccount.setName(bankAccountTmp.getName());
			bankAccount.setAccount(bankAccountTmp.getAccount());
			bankAccount.setOperIn("I");
			bankAccount.setRecUpdOpr(String.valueOf(op.getId()));
			bankAccount.setRecCrtTs(currentDate);
			baseDao.editSave(bankAccount);
			logger.info("----添加商户["+merinfoNo+"]结算信息正式表成功------");
			
			//添加业务受理及服务信息
			TblMchtBusiness  tmbusiness = new TblMchtBusiness();
			tmbusiness.setMchtCd(merinfoNo);//商户号
			tmbusiness.setFeeMoneyCd("RMB");
			tmbusiness.setFeeModeType("0");
			tmbusiness.setFeeHoliday("0");
			tmbusiness.setServiceFeeStart(Constance.formateDate1());
			tmbusiness.setServiceFeeYesno("0");
			tmbusiness.setRecUpdOpr(String.valueOf(op.getId()));
			tmbusiness.setRecCrtTs(currentDate);
			tmbusiness.setOperIn("I");
			baseDao.editSave(tmbusiness);
			logger.info("----添加商户["+merinfoNo+"]业务受理正式表成功------");
			
			//产品信息 
			String[] productStr=newMerinfo.getProductStrs();	//开通POS功能的t1/t0产品保存
			List<TblMchtBizDeal> tblMchtBizDealList = getTblMchtBizDealA(productStr, merinfo.getGroupCD(), merinfoNo, String.valueOf(op.getId()), newMerinfo.getId());
			if(tblMchtBizDealList != null && tblMchtBizDealList.size() > 0){
				for(TblMchtBizDeal mBizDealLists : tblMchtBizDealList){
					baseDao.editSave(mBizDealLists);
					logger.info("-----添加商户["+merinfoNo+"]正式产品表[prodcd-->"+mBizDealLists.getProdCd()+"[transCd-->"+mBizDealLists.getTransCd()+"]成功-----");
				}
			}
			if(Arrays.asList(m_info.getProductCode()).contains(ConfigMerinfoUtil.UNIONPAY_FUNCTION) || Arrays.asList(m_info.getProductCode()).contains(ConfigMerinfoUtil.ZWPAY_FUNCTION)){
				List<String> productList = queryMchtBizDealChecked(newMerinfo.getId());	//没有开通POS功能的银联/支付宝微信产品保存
				if(productList != null && productList.size()>0){
					List<TblMchtBizDeal> mchtBizDeals = getMchtBizDealList(merinfoNo, productList, op);
					if(mchtBizDeals != null && mchtBizDeals.size()>0){
						for(TblMchtBizDeal tblMchtBizDeal : mchtBizDeals){
							baseDao.editSave(tblMchtBizDeal);
							logger.info("-----添加商户["+merinfoNo+"]扫码类正式产品表[prodcd-->"+tblMchtBizDeal.getProdCd()+"[transCd-->"+tblMchtBizDeal.getTransCd()+"]成功-----");
						}
					}
				}
			}
			
			//手续费
			List<TblEditMchtBizFee> feeList=newMerinfo.getFee();
			if(null!=feeList && feeList.size()>0){
				for (TblEditMchtBizFee tmpTeb : feeList) {
					String prodCd = tmpTeb.getProdCd();
					if(null != prodCd){
						if(ConfigMerinfoUtil.T1_FUNCTION.equals(prodCd) || ConfigMerinfoUtil.T0_FUNCTION.equals(prodCd)){	//t1/t0手续费
							TblMchtBizFee mchtBizFeett = getTblMchtBizFeeTT(merinfoNo, tmpTeb, String.valueOf(op.getId()));
							if(mchtBizFeett != null){
								baseDao.editSave(mchtBizFeett);
								logger.info("-----添加商户["+merinfoNo+"]正式银行卡T1/T0手续费表[prodcd-->"+mchtBizFeett.getProdCd()+"][sub_biz_cd-->"+mchtBizFeett.getSubBizCd()+"[mcht_fee_percent-->"+mchtBizFeett.getMchtFeePercent()+"]成功-----");
							}
						}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(prodCd)){	//银联扫码手续费
							List<TblMchtBizFee> utblMchtBizFees = getMchtBizFeeSList(tmpTeb, merinfoNo, op, prodCd);
							if(utblMchtBizFees != null && utblMchtBizFees.size() > 0){
								for(TblMchtBizFee umchtBizFee : utblMchtBizFees){
									baseDao.editSave(umchtBizFee);
									logger.info("-----添加商户["+merinfoNo+"]正式银联扫码手续费表[prodcd-->"+umchtBizFee.getProdCd()+"][sub_biz_cd-->"+umchtBizFee.getSubBizCd()+"[mcht_fee_percent-->"+umchtBizFee.getMchtFeePercent()+"]成功-----");
								}
							}
						}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(prodCd)){	//支付宝微信手续费
							List<TblMchtBizFee> ztblMchtBizFees = getMchtBizFeeSList(tmpTeb, merinfoNo, op, prodCd);
							if(ztblMchtBizFees != null && ztblMchtBizFees.size() > 0){
								for(TblMchtBizFee zMchtBizFee : ztblMchtBizFees){
									baseDao.editSave(zMchtBizFee);
									logger.info("-----添加商户["+merinfoNo+"]正式支付宝微信手续费表[prodcd-->"+zMchtBizFee.getProdCd()+"][sub_biz_cd-->"+zMchtBizFee.getSubBizCd()+"[mcht_fee_percent-->"+zMchtBizFee.getMchtFeePercent()+"]成功-----");
								}
							}
						}else if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(prodCd) || ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(prodCd))){
							TblMchtBizFee mchtBizFeeDtt = getMchtBizFeeDtt(tmpTeb, prodCd, merinfoNo, String.valueOf(op.getId()));
							if(mchtBizFeeDtt != null){
								baseDao.editSave(mchtBizFeeDtt);
								logger.info("-----添加商户["+merinfoNo+"]直连T1/T0贷记卡、借记卡正式手续费表[prodcd-->"+mchtBizFeeDtt.getProdCd()+"][sub_biz_cd-->"+mchtBizFeeDtt.getSubBizCd()+"[mcht_fee_percent-->"+mchtBizFeeDtt.getMchtFeePercent()+"]成功-----");
							}
						}
					}
				}
				//为t0产品添加服务费、划付费
				if(Arrays.asList(m_info.getProductCode()).contains(ConfigMerinfoUtil.T0_FUNCTION)){
					List<TblMchtBizFee> mchtBizFeeYList = getTblMchtBizFeeYT1(merinfoNo, String.valueOf(op.getId()));
					if(mchtBizFeeYList != null && mchtBizFeeYList.size() > 0){
						for(TblMchtBizFee mchtBizFeet : mchtBizFeeYList){
							baseDao.editSave(mchtBizFeet);
							logger.info("-----添加商户["+merinfoNo+"]正式手续费表[prodcd-->"+mchtBizFeet.getProdCd()+"][sub_biz_cd-->"+mchtBizFeet.getSubBizCd()+"[mcht_fee_percent-->"+mchtBizFeet.getMchtFeePercent()+"]成功-----");
						}
					}
				}
				if(Arrays.asList(m_info.getProductCode()).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1)){		//直连商户T1-除贷记卡、借记卡外的产品手续费保存
					List<TblMchtBizFee> mchtBizFeeT1List = getTblMchtBizFeeDT1(merinfoNo, String.valueOf(op.getId()));
					if(mchtBizFeeT1List != null && mchtBizFeeT1List.size() > 0){
						for(TblMchtBizFee mchtBizFeesBizFees : mchtBizFeeT1List){
							baseDao.editSave(mchtBizFeesBizFees);
							logger.info("-----添加商户["+merinfoNo+"]直连T1除贷记卡、借记卡外正式手续费表[prodcd-->"+mchtBizFeesBizFees.getProdCd()+"][sub_biz_cd-->"+mchtBizFeesBizFees.getSubBizCd()+"[mcht_fee_percent-->"+mchtBizFeesBizFees.getMchtFeePercent()+"]成功-----");
						}
					}
				}
				if(Arrays.asList(m_info.getProductCode()).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0)){		//直连商户T0-除贷记卡、借记卡外的产品手续费保存
					List<TblMchtBizFee> mchtBizFeeT0List = getTblMchtBizFeeDT0(merinfoNo, String.valueOf(op.getId()));
					if(mchtBizFeeT0List != null && mchtBizFeeT0List.size() > 0){
						for(TblMchtBizFee mchtBizFeesBizFee : mchtBizFeeT0List){
							baseDao.editSave(mchtBizFeesBizFee);
							logger.info("-----添加商户["+merinfoNo+"]直连T0除贷记卡、借记卡外正式手续费表[prodcd-->"+mchtBizFeesBizFee.getProdCd()+"][sub_biz_cd-->"+mchtBizFeesBizFee.getSubBizCd()+"[mcht_fee_percent-->"+mchtBizFeesBizFee.getMchtFeePercent()+"]成功-----");
						}
					}
				}
			}
			///////图片问题 
			List<TblEditMchtPicture> picList=m_info.getPictrueList();
			int k=8;//管理平台进件最少8张
			if(null != m_info.getExt3() && m_info.getExt3().equals("2")){
				k=5;//app 进件最少5张
			}
			if(null!=picList && picList.size()>=k ){
				for (int j=0;j<picList.size();j++) {
					TblEditMchtPicture tmpPic=picList.get(j);
					TblMchtPicture pictrue=new TblMchtPicture();
					
					pictrue.setMchtCd(merinfoNo);//商户号
					pictrue.setUrl(tmpPic.getUrl().trim());//图片地址
					pictrue.setPindex(1);//顺序默认
					//名称
					Random ra=new Random();
					int random=1000+ra.nextInt(8999);
					int first=pictrue.getUrl().trim().indexOf("mid=")+4;
					int sencond=pictrue.getUrl().trim().lastIndexOf("&");
					if(first>4 && sencond>0){
						pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
						pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
						pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
					}else{
						String b=pictrue.getUrl().trim().substring(pictrue.getUrl().lastIndexOf("&")+1);
						pictrue.setPcode("code");//拆封名称去掉后缀
						pictrue.setFileName(b);//名称
						pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
					}
					pictrue.setDocType("00");
					pictrue.setSystemflag("00");
					pictrue.setStatus("0");
					pictrue.setRecOprId("I");//插入操作
					pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
					pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
					baseDao.editSave(pictrue);
					logger.info("----添加商户["+merinfoNo+"]图片正式表成功[file_id-->"+"FILE_ID"+merinfoNo+j+"]");
				}
			}else{
				 throw new ServiceException("请检查图片信息");
			}
			logger.info("----添加代理商商户关系开始--------");
			long a=merchantDao.addMerinfoAgentRelations(merinfoNo,merinfo.getNameBusi(),Long.parseLong(m_info.getExt1()));//调用存储过程添加代理商、商户关系表
			if(a>0){
				logger.info("----添加代理商商户关系成功共计["+a+"]个上级--------");
			} 
			logger.info("----添加操作员表开始["+merinfoNo+"]--------");
			Operators ops = new Operators();
			ops.setAccountNo(merinfoNo);
			ops.setRealName(merinfo.getNameBusi());
			String pwd = MD5Utils.MD5Encode("123456");
			ops.setPwd(pwd);
			ops.setValidEndDate(DateUtil.getYear(new Date(), +1, "yyyy-MM-dd HH:mm:ss"));// 操作员有效期
			ops.setValidStartDate(Constance.formateDateTime());// 有效期开始日期
			ops.setMobile(merinfo.getContactPhoneNo());// 手机号
			ops.setOrgCode(merinfo.getBankBelongCd());// 机构
			ops.setStatus(OperatorsStatus.OK.getCode());// 状态
			ops.setSuperiorId(Long.parseLong(merinfo.getExt1()));// 父类id
			ops.setOperators(merinfo.getRecUpdOpr());// op
			ops.setRoleType(Role.MERCHANT.getCode());// 角色类别
			ops.setFlag("0");
			ops.setCardType("01");
			ops.setCardNo(merinfo.getCertifNo());
			ops.setBankDeposit(bankAccountTmp.getBankName());
			ops.setBankAcctNo(bankAccountTmp.getAccount());
			ops.setBankAcctName(bankAccountTmp.getName());
			ops.setBank_no(bankAccountTmp.getBankCode());
			String hql_agent=" from Operators   WHERE  id=?";
			Object[] agent_id={Long.parseLong(merinfo.getExt1())};
			Operators fatherOp=(Operators)baseDao.createQueryUniqueResult(hql_agent, agent_id);
			if(null!=fatherOp){
				ops.setCompanyid(fatherOp.getCompanyid());//所属公司
				ops.setOneagentid(fatherOp.getOneagentid());//所属一级代理
			}
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String time = sdf.format(dt);
			ops.setUpdatePWD(time);
			ops.setSex("1");
			baseDao.editSave(ops);
			logger.info("----配置商户菜单开始--------");
			merchantDao.addMerinfoModule(merinfoNo, "piliangshenhe");//调用存储过程添加代理商、商户关系表
 
			
			logger.info("----添加商户["+merinfoNo+"]信息完成----");
			baseDao.addSyslog(SysLogType.MERCHANT_LAST_AUDITING.getCode(),
							SysLogType.MERCHANT_LAST_AUDITING.getName(),
							op.getAccountNo(), 
							"操作员【" + op.getAccountNo()+ "】，终审商户【" + merinfo.getId() + "】成功");
			return MerinfoReturninfo.S_22.getName()+"_"+merinfoNo+"_"+merinfo.getContactPhoneNo();
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException("审核商户信息失败",e);
		}

	}
	
	/**
	 * 查询需要审核的商户数据{ 48502000机构下、间连的、结算账户对私的、排除 特定优惠类mcc 的}
	 * */
	public List<?> queryNeedCheckMerinfo(int count)throws ServiceException{
		try {
			 String mcc_stop=Utils.getConfigValue("MCC_STOP");//不需要审核的mcc
			 String hql=" from TblEditMchtInf t "
						+ " where t.status='00' and t.bankBelongCd='48502000' "
						+ " and not exists (select 1 from AuditingItem a where a.obj_Audited=t.id and a.audit_code='3003' and  a.result_code='02') "
						+ " and t.groupCD='0' and t.approvalUserName='0'  and  t.upMccCd not in ("+mcc_stop+")"
						+ " order by t.recCrtTs asc ";
			List<?> list=pageDao.findAll(hql, null, 0, count);
			return list;
		} catch (DaoException e) {
			logger.error("----查询需要审核的商户数据失败------",e);
			throw  new  ServiceException("-----查询需要审核的商户数据失败----",e);
		}
	}
	
	
	/**
	 * 批量审核（风控主管）
	 * */
	@Transactional(rollbackFor = { ServiceException.class })
	public  void  checkMerinfo(TblEditMchtInf tmpMerinfo,Operators op) throws ServiceException {
			try { 
						//审核代码
						AuditingItem  audit=new AuditingItem();
						audit.setAudit_code(AuditingType.MERCHANT_LAST_AUDITING.getCode());//获取审核编码
						audit.setAudit_name(AuditingType.MERCHANT_LAST_AUDITING.getName());//获取审核名称
						audit.setOperators("cj");//操作账号 (批量审核固定人员为风控主管‘cj’)
					
						logger.info("-------开始审核商户{"+tmpMerinfo.getId()+"}----------");
						audit.setObj_Audited(tmpMerinfo.getId());//审核对象
						Object[] midParam={tmpMerinfo.getId()};
						
						if(null==tmpMerinfo.getUcBccd() || tmpMerinfo.getUcBccd().length()<5 
									|| tmpMerinfo.getUcBccd().substring(4).equals("null")){
							logger.info("-----32域不正常，进行驳回-----");
							audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
							audit.setResult_detail(MerinfoReturninfo.S_27.getName());
							baseDao.editSave(audit);//添加审核意见
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						if(null==tmpMerinfo.getUpMccCd() ){
							logger.info("-----mcc不正常，进行驳回-----");
							audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
							audit.setResult_detail(MerinfoReturninfo.S_28.getName());
							baseDao.editSave(audit);//添加审核意见
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						if(null==tmpMerinfo.getContactPhoneNo()|| tmpMerinfo.getContactPhoneNo().length()!=11){
							logger.info("-----手机号不正常，进行驳回-----");
							audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
							audit.setResult_detail(MerinfoReturninfo.S_41.getName());
							baseDao.editSave(audit);//添加审核意见
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						//已被审核过的商户
						String countSql ="SELECT count(1) FROM tbl_mcht_inf t WHERE t.busi_rang=? ";
						Object obj=sqlBaseDao.findObj(countSql, midParam);
						if(null!=obj && Long.parseLong(obj.toString())>0){
							logger.info("-----已经审核过该商户号，进行驳回-----");
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						String accountHql="from TblEditMchtBankAccount t where t.ownerCd=?";
						TblEditMchtBankAccount  bankAccountTmp= (TblEditMchtBankAccount)pageDao.createQueryUniqueResult(accountHql, midParam);
						if(null!=bankAccountTmp){
							tmpMerinfo.setBankAccount(bankAccountTmp);
						}else{
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						String validate=validateCount(tmpMerinfo,op);
						String str=validateExist(tmpMerinfo,op);//校验 身份证  营业执照   银行卡 非法人身份证 是否被风控
						if(null!=validate  || null!=str ){ //主动驳回 
							logger.info("-----风控限制，进行驳回-----");
							audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
							audit.setResult_detail(validate);
							baseDao.editSave(audit);//添加审核意见
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						
						 
						String serial=merchantDao.handleMerchantno("850", tmpMerinfo.getUcBccd().substring(4), tmpMerinfo.getUpMccCd());
						String merinfoNo="850"+tmpMerinfo.getUcBccd().substring(4)+tmpMerinfo.getUpMccCd()+serial;
						logger.info("------开始插入正式表：临时商户号："+tmpMerinfo.getId()+"---->正式商户号："+merinfoNo);
						if(merinfoNo.length()!=15 || merinfoNo.indexOf("-")>-1){
							logger.info("当前mcc["+tmpMerinfo.getUpMccCd()+"]| 32code["+tmpMerinfo.getUcBccd()+"]  ");
							audit.setResult_code(AuditingResultCodeType.REFUSE.getCode());
							audit.setResult_detail(MerinfoReturninfo.S_1.getName());
							baseDao.editSave(audit);//添加审核意见
							tmpMerinfo.setStatus(MerinfoStatus.S_4.getCode());
							baseDao.editUpdate(tmpMerinfo);//更新
							return;
						}
						 
						//更新原来状态
						tmpMerinfo.setStatus(MerinfoStatus.S_0.getCode());
						baseDao.editUpdate(tmpMerinfo);//更新
						
						
						 Date currentDate=new Date();
						 TblMchtInf merinfo=new TblMchtInf();
						 merinfo.setId(merinfoNo);
						 merinfo.setBusiRang(tmpMerinfo.getId());/////保存临时表的商户号
						 merinfo.setSn(serial);
						 merinfo.setAipBranCd(tmpMerinfo.getAipBranCd());
						 merinfo.setOriChnl(tmpMerinfo.getOriChnl());
						 merinfo.setBankBelongCd(tmpMerinfo.getBankBelongCd());
						 String applDate = DateUtil.getDate(new Date(), 0, "yyyy-MM-dd");
						 merinfo.setApplDate(applDate);//应用时间 
						 merinfo.setApprDate(tmpMerinfo.getRecCrtTs());//进件时间
						 merinfo.setName(tmpMerinfo.getName());
						 merinfo.setNameBusi(tmpMerinfo.getNameBusi());
						 merinfo.setBusiLiceNo(tmpMerinfo.getBusiLiceNo());
						 merinfo.setBusiMain(tmpMerinfo.getBusiMain());
						 merinfo.setCertif(tmpMerinfo.getCertif());
						 merinfo.setCertifType(tmpMerinfo.getCertifType());
						 merinfo.setCertifNo(tmpMerinfo.getCertifNo());
						 merinfo.setDvpBy(tmpMerinfo.getDvpBy()); //是否法人结算账户
						 merinfo.setNationCd(tmpMerinfo.getNationCd()); //商户类型
						 merinfo.setGroupCD(tmpMerinfo.getGroupCD()); //连接方式 直连间连
						 merinfo.setProvCd(tmpMerinfo.getProvCd());
						 merinfo.setCityCd(tmpMerinfo.getCityCd());
						 merinfo.setAreaCd(tmpMerinfo.getAreaCd());
						 merinfo.setRegAddr(tmpMerinfo.getRegAddr());
						 merinfo.setContactName(tmpMerinfo.getContactName());
						 merinfo.setContactPhoneNo(tmpMerinfo.getContactPhoneNo());
						 merinfo.setIsGroup(tmpMerinfo.getIsGroup());  //商户等级
						 merinfo.setMoneyToGroup(tmpMerinfo.getMoneyToGroup());
						 merinfo.setStlmWay(tmpMerinfo.getStlmWay());
						 merinfo.setStlmWayDesc(tmpMerinfo.getStlmWayDesc());//非法人的身份证
						 merinfo.setStlmInsCircle(tmpMerinfo.getStlmInsCircle());
						 merinfo.setStatus(MerinfoStatus.S_0.getCode());//正常状态
						 merinfo.setIsUpStandard(tmpMerinfo.getIsUpStandard());
						 merinfo.setApprovalUserName(tmpMerinfo.getApprovalUserName()); //账户对公对私
						 merinfo.setBillingType(tmpMerinfo.getBillingType());
						 merinfo.setExt1(tmpMerinfo.getExt1());
						 merinfo.setExt2(tmpMerinfo.getExt2());
						 merinfo.setExt3(tmpMerinfo.getExt3());
						 merinfo.setExt4(tmpMerinfo.getExt4());
						 merinfo.setRecCrtTs(currentDate);
						 merinfo.setOperIn("I");
						 merinfo.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());//进件人员
						 merinfo.setOriChnlDesc("40002");//保存审核人员id
						 merinfo.setMcc(tmpMerinfo.getUpMccCd());
						 merinfo.setUpMccCd(tmpMerinfo.getUpMccCd());//mcc
						 merinfo.setUcBccd(tmpMerinfo.getUcBccd());//32域
						 merinfo.setUcBccdArea(tmpMerinfo.getUcBccdArea());
						 baseDao.editSave(merinfo);
						 logger.info("---正式商户表添加["+merinfoNo+"]成功---");
						
						
						
					//////结算账户信息	
						if(null!=bankAccountTmp){
							TblMchtBankAccount bankAccount=new TblMchtBankAccount();
							bankAccount.setOwnerCd(merinfoNo);//商户号
							bankAccount.setAccountType(bankAccountTmp.getAccountType()); //账户类型  **********************************
							bankAccount.setRecCrtTs(bankAccountTmp.getRecCrtTs());//记录时间
							bankAccount.setUcBccd(bankAccountTmp.getUcBccd());//开户行选择
							bankAccount.setBankCode(bankAccountTmp.getBankCode());
							bankAccount.setBankName(bankAccountTmp.getBankName());
							bankAccount.setName(bankAccountTmp.getName());
							bankAccount.setAccount(bankAccountTmp.getAccount());
							bankAccount.setOperIn("I");
							bankAccount.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
							bankAccount.setRecCrtTs(currentDate);
							baseDao.editSave(bankAccount);
							logger.info("----添加商户["+merinfoNo+"]结算信息正式表成功------");
						}
						////终端和终端风控信息
						String termHql="from TblEditTermInf t where t.id.MchtCd=?";
						List<?> termList=pageDao.queryAll(termHql, midParam);
						if(null!=termList && termList.size()>0){
							for (Object object : termList) {
								String sql="SELECT SEQ_DEVICE_CD.nextval CURRENTS FROM dual ";
								Object currentSeq=sqlBaseDao.findObj(sql, null);
								TblEditTermInf tmpTerm=(TblEditTermInf)object;
								TblTermInf  terminfo=new TblTermInf();
								TblTermInfId terminfoId=new TblTermInfId();
								terminfoId.setMchtCd(merinfoNo);
								terminfoId.setTermId(tmpTerm.getId().getTermId());
								terminfo.setId(terminfoId);
								terminfo.setStatus(tmpTerm.getStatus());//初始状态
								terminfo.setTermTp(tmpTerm.getTermTp());
								terminfo.setBelong(tmpTerm.getBelong());
								terminfo.setBelongSub(tmpTerm.getBelongSub());
								terminfo.setTmnlMoneyIntype(tmpTerm.getTmnlMoneyIntype());
								terminfo.setTmnlMoney(tmpTerm.getTmnlMoney());
								terminfo.setInstalllocation(tmpTerm.getInstalllocation());
								terminfo.setTmnlIntype(tmpTerm.getTmnlIntype());
								terminfo.setDeviceCd("YJ"+String.valueOf(currentSeq));//终端序列号
								terminfo.setRecOprId("I");
								terminfo.setRecCrtTs(currentDate);//记录时间
								terminfo.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
								terminfo.setDialOut(tmpTerm.getDialOut());//终端呼出号码，默认暂定无用处
								baseDao.editSave(terminfo);
							}
						}
						
						//终端风控规则
						String riskHql="from TblEditTermRiskCfg t where t.id.MchtCd=?";
						List<?> riskList=pageDao.queryAll(riskHql, midParam);
						if(null!=riskList && riskList.size()>0){
							for (Object object : riskList) {
								TblEditTermRiskCfg  tmpRisk=(TblEditTermRiskCfg)object;
								TblTermRiskCfg risk= new TblTermRiskCfg();
								TblTermRiskCfgId riskId=new TblTermRiskCfgId();
								riskId.setMchtCd( merinfoNo);//商户号
								riskId.setTermId(tmpRisk.getId().getTermId());//终端
								riskId.setCardType(tmpRisk.getId().getCardType());
								risk.setId(riskId);
								risk.setTotalLimitmoney(1000000);
								risk.setAccpetStartTime(tmpRisk.getAccpetStartTime());
								risk.setAccpetEndTime(tmpRisk.getAccpetEndTime());
								risk.setSingleLimitmoney(50000);
								risk.setSingleMinMoney(1);
								risk.setControlWay(tmpRisk.getControlWay());//控制方式
								risk.setTotalPeriod(tmpRisk.getTotalPeriod());//周期
								risk.setRecCrtTs(currentDate);
								risk.setRecOprId("I");
								risk.setOperIn("I");
								risk.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
								baseDao.editSave(risk);
								logger.info("-----正式风控表添加商户["+merinfoNo+"]的终端["+tmpRisk.getId().getTermId()+"]的卡状态为["+riskId.getCardType()+"]风控信息成功-----");
							}
						}
						
						
						
						//添加业务受理及服务信息
						TblMchtBusiness  tmbusiness = new TblMchtBusiness();
						tmbusiness.setMchtCd(merinfoNo);//商户号
						tmbusiness.setFeeMoneyCd("RMB");
						tmbusiness.setFeeModeType("0");
						tmbusiness.setFeeHoliday("0");
						tmbusiness.setServiceFeeStart(Constance.formateDate1());
						tmbusiness.setServiceFeeYesno("0");
						tmbusiness.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
						tmbusiness.setRecCrtTs(currentDate);
						tmbusiness.setOperIn("I");
						baseDao.editSave(tmbusiness);
						logger.info("----添加商户["+merinfoNo+"]业务受理正式表成功------");
						 
						
						//获取的产品信息
						String bizDelHql="from TblEditMchtBizDeal t where t.mchtCd=?";
						List<?> bizDelList=pageDao.queryAll(bizDelHql, midParam);
						if(null!=bizDelList && bizDelList.size()>0){
							for (Object object : bizDelList) {
								TblEditMchtBizDeal tbd=(TblEditMchtBizDeal)object;
								TblMchtBizDeal tmb=new TblMchtBizDeal();
								tmb.setMchtCd(merinfoNo);
								tmb.setProdCd(tbd.getProdCd());
								tmb.setBizCd(tbd.getBizCd());
								tmb.setTransCd(tbd.getTransCd());
								tmb.setOperIn("I");
								tmb.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
								tmb.setRecCrtTs(currentDate);
								tbd=null;
								baseDao.editSave(tmb);
							}
						}
						
						//获取手续费
						String feeHql=" from TblEditMchtBizFee t where t.mchtCd=? ";
						//String feeHql=" from TblEditMchtBizFee t where t.bizFeeId.mchtCd=? ";
						List<?> feeList=pageDao.queryAll(feeHql, midParam);
						if(null!=feeList && feeList.size()>0){
							for (Object object : feeList) {
								TblEditMchtBizFee tmpTeb=(TblEditMchtBizFee)object;
								//logger.info("-----"+tmpTeb.getBizFeeId().getMchtCd()+"--"+tmpTeb.getBizFeeId().getProdCd()+"--"+tmpTeb.getBizFeeId().getSubBizCd()+"--"+tmpTeb.getBizFeeId().getBizCd()+"---");
								TblMchtBizFee  teb=new TblMchtBizFee();
								 
								 
								teb.setMchtCd(merinfoNo);//商户号
								/*teb.setProdCd(tmpTeb.getBizFeeId().getProdCd());//产品  业务类型
								teb.setBizCd(tmpTeb.getBizFeeId().getBizCd());
								teb.setSubBizCd(tmpTeb.getBizFeeId().getSubBizCd());*/
								teb.setProdCd(tmpTeb.getProdCd());//产品  业务类型
								teb.setBizCd(tmpTeb.getBizCd());
								teb.setSubBizCd(tmpTeb.getSubBizCd());
								teb.setMchtFeePercent(tmpTeb.getMchtFeePercent());
								teb.setMchtFeePctMax(tmpTeb.getMchtFeePctMax());
								teb.setMchtFeeMd("0"); ///未知参数不能为空
								teb.setMchtAFeeSame("0"); ///未知参数不能为空
								teb.setMchtAFeeMd("0"); ///未知参数不能为空
								teb.setOperIn("I");
								teb.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());
								teb.setRecCrtTs(currentDate);
								baseDao.editSave(teb);
								logger.info("-----添加商户["+merinfoNo+"]正式手续费表[prodcd-->"+teb.getProdCd()+"][sub_biz_cd-->"+teb.getSubBizCd()+"]成功-----");
							}
						}
						
						//获取图片信息
						String picHql="from TblEditMchtPicture t where t.MchtCd=?";
						List<?> picList=pageDao.queryAll(picHql, midParam);
						
						if(null!=picList && picList.size()>0){
							int i=0;
							for (Object object : picList) {
								TblEditMchtPicture tmpPic=(TblEditMchtPicture)object;
								TblMchtPicture pictrue=new TblMchtPicture();
								pictrue.setMchtCd(merinfoNo);//商户号
								pictrue.setUrl(tmpPic.getUrl().trim());//图片地址
								pictrue.setPindex(tmpPic.getPindex());//顺序默认
								//名称
								  
								int first=pictrue.getUrl().trim().indexOf("mid=")+4;
								int sencond=pictrue.getUrl().trim().lastIndexOf("&");
								if(first>4 && sencond>0){
									pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
									pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
									//pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+i);//主键id
									pictrue.setFileId("FILE_ID"+merinfoNo+"_"+i);//主键id
								}else{
									String b=pictrue.getUrl().trim().substring(pictrue.getUrl().lastIndexOf("&")+1);
									pictrue.setPcode("code");//拆封名称去掉后缀
									pictrue.setFileName(b);//名称
									pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
								}
								
								pictrue.setDocType("00");
								pictrue.setSystemflag("00");
								pictrue.setStatus("0");
								pictrue.setRecOprId("I");//插入操作
								pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
								pictrue.setRecUpdOpr(tmpMerinfo.getRecUpdOpr());//操作员id
								baseDao.editSave(pictrue);
								i++;
								logger.info("----添加商户["+merinfoNo+"]图片正式表成功[file_id-->"+"FILE_ID"+pictrue.getFileId()+"]");
							}
						}
						logger.info("----添加代理商商户关系开始--------");
						long a=merchantDao.addMerinfoAgentRelations(merinfoNo,merinfo.getNameBusi(),Long.parseLong(tmpMerinfo.getRecUpdOpr()));//调用存储过程添加代理商、商户关系表
						if(a>0){
							logger.info("----添加代理商商户关系成功共计["+a+"]个上级--------");
						}
						logger.info("----添加操作员表开始["+merinfoNo+"]--------");
						Operators ops = new Operators();
						ops.setAccountNo(merinfoNo);
						ops.setRealName(merinfo.getNameBusi());
						String pwd = MD5Utils.MD5Encode("123456");
						ops.setPwd(pwd);
						ops.setValidEndDate(DateUtil.getYear(new Date(), +1, "yyyy-MM-dd HH:mm:ss"));// 操作员有效期
						ops.setValidStartDate(Constance.formateDateTime());// 有效期开始日期
						ops.setMobile(merinfo.getContactPhoneNo());// 手机号
						ops.setOrgCode(merinfo.getBankBelongCd());// 机构
						ops.setStatus(OperatorsStatus.OK.getCode());// 状态
						ops.setSuperiorId(Long.parseLong(merinfo.getExt1()));// 父类id
						ops.setOperators(merinfo.getRecUpdOpr());// op
						ops.setRoleType(Role.MERCHANT.getCode());// 角色类别
						ops.setFlag("0");
						ops.setCardType("01");
						ops.setCardNo(merinfo.getCertifNo());
						ops.setBankDeposit(bankAccountTmp.getBankName());
						ops.setBankAcctNo(bankAccountTmp.getAccount());
						ops.setBankAcctName(bankAccountTmp.getName());
						ops.setBank_no(bankAccountTmp.getBankCode());
						String hql_agent=" from Operators   WHERE  id=?";
						Object[] agent_id={Long.parseLong(merinfo.getExt1())};
						Operators fatherOp=(Operators)baseDao.createQueryUniqueResult(hql_agent, agent_id);
						if(null!=fatherOp){
							ops.setCompanyid(fatherOp.getCompanyid());//所属公司
							ops.setOneagentid(fatherOp.getOneagentid());//所属一级代理
						}
						Date dt = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						String time = sdf.format(dt);
						ops.setUpdatePWD(time);
						ops.setSex("1");
						baseDao.editSave(ops);
						logger.info("----配置商户菜单开始--------");
						merchantDao.addMerinfoModule(merinfoNo, "piliangshenhe");//调用存储过程添加代理商、商户关系表
			 
						baseDao.addSyslog(SysLogType.MERCHANT_LAST_AUDITING.getCode(),
								SysLogType.MERCHANT_LAST_AUDITING.getName(),
								"cj", 
								"操作员【cj】，终审商户【" + merinfo.getId() + "】成功");
						 
					 
				 
			} catch (DaoException e) {
				logger.error("批量审核商户信息失败",e);
				throw new ServiceException("批量审核商户信息失败",e);
			}
	}
	/**
	 * 修改图片信息
	 * @param merchantInfo  页面商户信息
	 * @param op 操作员信息
	 * @return void 
	 * @author zbl
	 * */
	@Transactional(rollbackFor = { ServiceException.class })
	public String modifyPicInfo(TblMchtInf merinfo, Operators op) throws ServiceException {
		try {
			Object[] param={merinfo.getBusiRang()};
			Object[] params={merinfo.getId()};
			/////商户图片
			List<TblMchtPicture> pictrueList=merinfo.getPictrueList();
			if(null!=pictrueList && pictrueList.size()>=8){
				//临时图片信息
				String sel_pic_sql = "select count(1) from TBL_EDIT_MCHT_PICTURE T WHERE T.MCHT_CD=?";
				Object sel_pic_cou = sqlBaseDao.findObj(sel_pic_sql, param);
				if(Integer.parseInt(String.valueOf(sel_pic_cou)) > 0 ){
					String pic_sql="DELETE FROM TBL_EDIT_MCHT_PICTURE T WHERE T.MCHT_CD=?";
					int editDelCount = sqlBaseDao.removeBySql(pic_sql,param);
					
					if(editDelCount<1){
						logger.info(merinfo.getId()+"图片临时表图片信息删除失败");
						throw new ServiceException(merinfo.getId()+"图片临时表图片信息删除失败");
					}
					
				}
				
				
				//正式图片信息
				String sel_pic_sql_zs = "select count(1) from TBL_MCHT_PICTURE T WHERE T.MCHT_CD=?";
				Object sel_pic_zs_cou = sqlBaseDao.findObj(sel_pic_sql_zs, params);
				
				if(Integer.parseInt(String.valueOf(sel_pic_zs_cou))>0){
					String pic_sql_zs="DELETE FROM TBL_MCHT_PICTURE T WHERE T.MCHT_CD=?";
					int delCount = sqlBaseDao.removeBySql(pic_sql_zs,params);
					
					if(delCount<1){
						logger.info(merinfo.getId()+"图片信息删除失败");
						throw new ServiceException(merinfo.getId()+"图片信息删除失败");
					}
				}
				
				
				logger.info("----删除["+merinfo.getBusiRang()+"]临时图片信息表信息成功-----");
				logger.info("----删除["+merinfo.getId()+"]图片信息表信息成功-----");
				
				for (TblMchtPicture pi : pictrueList) {
					if(pi.getUrl()==null || pi.getUrl().equals("") || pi.getUrl().length()<1){
						continue;
					}
					//临时图片信息表
					TblEditMchtPicture pictrue=new TblEditMchtPicture();
					
					//正式图片信息表
					TblMchtPicture pic=new TblMchtPicture();

					
					
					pictrue.setMchtCd(merinfo.getBusiRang());//临时商户号
					pic.setMchtCd(merinfo.getId());//正式商户号
					
					pictrue.setUrl(pi.getUrl().trim());//图片地址
					pic.setUrl(pi.getUrl().trim());//图片地址
					
					pictrue.setPindex(1);//顺序默认
					pic.setPindex(1);//顺序默认
					
					Random ra=new Random();
					int random=1000+ra.nextInt(8999);
					int first=pi.getUrl().trim().indexOf("mid=")+4;
					int sencond=pi.getUrl().trim().lastIndexOf("&");
					if(first>4 && sencond>0){
						pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
						pic.setFileName(pic.getUrl().substring(first, sencond));//名称
						
						pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
						pic.setPcode(pic.getFileName().substring(0, pic.getFileName().indexOf(".")));//拆封名称去掉后缀
						
						pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
						pic.setFileId("FILE_ID"+pic.getFileName().substring(0, pic.getFileName().indexOf("."))+"_"+random);//主键id
					}else{
						String b=pi.getUrl().trim().substring(pi.getUrl().lastIndexOf("&")+1);
						pictrue.setPcode("code");//拆封名称去掉后缀
						pic.setPcode("code");//拆封名称去掉后缀
						
						pictrue.setFileName(b);//名称
						pic.setFileName(b);//名称
						
						pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
						pic.setFileId("FILE_ID"+pic.getFileName());//主键id
					}
					pictrue.setDocType("00");
					pic.setDocType("00");
					
					pictrue.setSystemflag("00");
					pic.setSystemflag("00");
					
					pictrue.setStatus("0");
					pic.setStatus("0");
					
					pictrue.setRecOprId("I");//插入操作
					pic.setRecOprId("I");//插入操作
					
					pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
					pic.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
					
					pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
					pic.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
					baseDao.editSave(pictrue);
					baseDao.editSave(pic);
					
					logger.info("----添加["+merinfo.getBusiRang()+"]图片信息[file_id-->"+pictrue.getFileId()+"]成功-----");
					logger.info("----添加["+merinfo.getId()+"]图片信息[file_id-->"+pic.getFileId()+"]成功-----");
				}
			}else{
				throw new ServiceException(MerinfoReturninfo.S_5.getName());
			}
			
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException("完善商户信息出错");
		}
		
		return "修改图片信息成功";
	}
	
	/**
	 * 驳回进件商户信息重新提交
	 * @param merchantInfo  页面商户信息
	 * @param op 操作员信息
	 * @return void 
	 * @author zbl
	 * */
	@Transactional(rollbackFor = { ServiceException.class })
	public String editMerinfo(TblEditMchtInf merinfoTmp, Operators op ,String merRejectFlag) throws ServiceException {
		try {
			String str=validateForm(merinfoTmp, op);
			if(null!=str) return str;
			 
			String validateStr=validateCount(merinfoTmp,op);//
			if(null!=validateStr) return validateStr;
			
			String validate=validateExist(merinfoTmp,op);//校验 身份证  营业执照   银行卡 非法人身份证 是否被风控
			if(null!=validate) return validate;
			
			 Object[] param={merinfoTmp.getId()};
			String settle_hql="from TblEditMchtBankAccount t where t.ownerCd=?";
			TblEditMchtBankAccount bankAccount=(TblEditMchtBankAccount)baseDao.createQueryUniqueResult(settle_hql,param );
			bankAccount.setName(merinfoTmp.getBankAccount().getName());
			bankAccount.setAccount(merinfoTmp.getBankAccount().getAccount());
			bankAccount.setBankName(merinfoTmp.getBankAccount().getBankName());
			bankAccount.setBankCode(merinfoTmp.getBankAccount().getBankCode());
			if(merinfoTmp.getBankAccount().getBankCode().length()>0){
				bankAccount.setUcBccd(merinfoTmp.getBankAccount().getBankCode().substring(0,3));
			}
			bankAccount.setRecUpdTs(new Date()); //驳回更新时间
			baseDao.editUpdate(bankAccount);//结算信息
			logger.info("-----["+merinfoTmp.getId()+"]完善结算信息成功----");
			//商户扩展信息
			TblEditMchtExtendInfo mchtExtendInfo = merinfoTmp.getMchtExtendInfo();
			if("2".equals(op.getGroupCd())){
				String mextend_hql="from TblEditMchtExtendInfo t where t.id=?";
				TblEditMchtExtendInfo mextend=(TblEditMchtExtendInfo)baseDao.createQueryUniqueResult(mextend_hql,param );
				if(mextend != null){
					mextend.setDevelopPerson(mchtExtendInfo.getDevelopPerson());
					mextend.setTermProperty(mchtExtendInfo.getTermProperty());
					mextend.setCertifStartDate(mchtExtendInfo.getCertifStartDate());
					mextend.setCertifEndDate(mchtExtendInfo.getCertifEndDate());
					mextend.setBusiLiceStartDate(mchtExtendInfo.getBusiLiceStartDate());
					mextend.setBusiLiceEndDate(mchtExtendInfo.getBusiLiceEndDate());
					mextend.setBackup5(mchtExtendInfo.getBackup5());
					baseDao.editUpdate(mextend); //商户扩展信息
					logger.info("-----驳回完善商户扩展信息成功-----商户号：["+merinfoTmp.getId()+"]-----end");
				}	
			}
			////终端信息
			List<TblEditTermInf> terminList=merinfoTmp.getTerminfoList();
			if(null!=terminList && terminList.size()>0){
				//删除原终端信息
				String ter_sql="DELETE FROM  TBL_EDIT_TERM_INF t WHERE t.MCHT_CD=?";
				int terCount=sqlBaseDao.removeBySql(ter_sql,param);//终端信息
				if(terCount>0){
					logger.info("----删除["+merinfoTmp.getId()+"]下终端成功开始完善----");
					String ter_risk_sql="DELETE FROM  TBL_EDIT_TERM_RISK_CFG t WHERE t.MCHT_CD=?";
					 sqlBaseDao.removeBySql(ter_risk_sql,param);//终端风控
					 logger.info("----删除["+merinfoTmp.getId()+"]下风控信息成功开始完善----");
				}
				int i=1;
				for (TblEditTermInf tb:terminList) {
					TblEditTermInfId tb_id=new TblEditTermInfId();
					String terId = "";
					if(i<10){
						terId="0000000"+i;
					}else{
						terId="000000"+i;
					}
					tb_id.setMchtCd(merinfoTmp.getId());//商户号
					tb_id.setTermId(terId); //终端号码
					tb.setId(tb_id);
					tb.setBelong("1");
					tb.setBelongSub(String.valueOf(op.getOrgCode()));
					tb.setStatus("01");//初始状态
					tb.setDeviceCd("YJ");//默认sn号码
					tb.setRecCrtTs(new Date());//记录时间
					tb.setDialOut("60000");//终端呼出号码，默认暂定无用处
					tb.setTmnlMoneyIntype("1");//押金收取方式 0按照商户 1按照终端
					baseDao.editSave(tb);
					logger.info("-----驳回完善终端信息成功-----商户号：["+merinfoTmp.getId()+"]终端号：["+terId+"]-----");
					//终端风控信息
					TblEditTermRiskCfg ttr=merinfoTmp.getTerminfoRisk();
					if(ttr!=null){//风控信息不为空
						for (int j = 0; j < 2; j++) { //借记卡01、贷记卡 00风控规则
							
							TblEditTermRiskCfgId  terRiskId=new TblEditTermRiskCfgId();
							if(j==0)//判断卡类型
									terRiskId.setCardType("00");
							else 
									terRiskId.setCardType("01");
							terRiskId.setMchtCd(merinfoTmp.getId());//商户号
							terRiskId.setTermId(terId);//终端号
							TblEditTermRiskCfg terRisk=new TblEditTermRiskCfg();
							terRisk.setId(terRiskId);
							terRisk.setAccpetStartTime(ttr.getAccpetStartTime()); //营业开始时间
							terRisk.setAccpetEndTime(ttr.getAccpetEndTime()); //营业结束时间
							terRisk.setRecCrtTs(new Date());//录入时间
							terRisk.setRecOprId("I");//插入操作标识符
							terRisk.setRecUpdOpr(String.valueOf(op.getId()));//操作员
							terRisk.setOperIn("I");//插入
							baseDao.editSave(terRisk);
							logger.info("-----驳回完善终端风控信息成功-----商户号：["+merinfoTmp.getId()+"]终端号：["+terId+"]的风控卡类型：["+terRiskId.getCardType()+"]-----");
						}
					}else{
						throw new ServiceException(MerinfoReturninfo.S_7.getName());
					}
					i++;
				}
				logger.info("-----驳回完善终端、终端风控信息成功-----商户号："+merinfoTmp.getId()+"-----end");
			}else{
				throw new ServiceException(MerinfoReturninfo.S_2.getName());
			} 
			
			///////产品信息
			String[] productCode=merinfoTmp.getProductCode();
			if(null!=productCode && productCode.length>0){
				///////手续费 
				List<TblEditMchtBizFee> feeList=merinfoTmp.getFee();
				if(null==feeList || feeList.size()<1) return MerinfoReturninfo.S_4.getName();
				//产品信息
				String deal_sql="DELETE FROM  TBL_EDIT_MCHT_BIZ_DEAL t WHERE t.MCHT_CD=?";
				sqlBaseDao.removeBySql(deal_sql,param);
				logger.info("----删除["+merinfoTmp.getId()+"]产品信息成功-----");
				//手续费
				String fees_sql="DELETE FROM TBL_EDIT_MCHT_BIZ_FEE T WHERE T.MCHT_CD=?";
				sqlBaseDao.removeBySql(fees_sql,param);
				logger.info("----删除["+merinfoTmp.getId()+"]手续费信息成功-----");
				//添加产品信息
				for (int j = 0; j < productCode.length; j++) {
					if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){	//银联扫码
						List<TblEditMchtBizDeal> unionpayBizDealList = getUnionpayMchtBizDealList(merinfoTmp, op);
						if(unionpayBizDealList != null && unionpayBizDealList.size() > 0){
							for(TblEditMchtBizDeal ubizDeal : unionpayBizDealList){
								baseDao.editSave(ubizDeal);
								logger.info("-----驳回完善银联扫码产品信息成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+ubizDeal.getProdCd()+"]-----");
							}
						}
					}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){	//支付宝微信
						List<TblEditMchtBizDeal> zwpayBizDealList = getZwpayMchtBizDealList(merinfoTmp, op);
						if(zwpayBizDealList != null && zwpayBizDealList.size() > 0){
							for(TblEditMchtBizDeal zbizDeal : zwpayBizDealList){
								baseDao.editSave(zbizDeal);
								logger.info("-----驳回完善支付宝微信产品信息成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+zbizDeal.getProdCd()+"]-----");
							}
						}
					}else if(Constant.STR_NUMBER_ONE.equals(merinfoTmp.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j])
							|| ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){	//直连T1/T0产品
						Map<String, String> dproMap=ConfigMerinfoUtil.getDirectProductList(productCode[j], false);
						List<TblEditMchtBizDeal> editMchtBizDealList = getDirectEditMchtBizDealList(dproMap, productCode[j], merinfoTmp.getId(), String.valueOf(op.getId()));
						if(editMchtBizDealList != null && editMchtBizDealList.size()>0){
							for(TblEditMchtBizDeal editMchtBizDeals : editMchtBizDealList){
								baseDao.editSave(editMchtBizDeals);
								logger.info("-----驳回完善直连T1/T0产品信息成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizDeals.getProdCd()+"]-----");
							}
						}
					}else{
						Map<String, String> proMap=ConfigMerinfoUtil.getPosFunction(productCode[j], false);		// 银行卡T1/T0产品
						List<TblEditMchtBizDeal> editMchtBizDealT = getEditMchtBizDealTList(proMap, merinfoTmp.getId(), productCode[j], String.valueOf(op.getId()));
						if(editMchtBizDealT != null &&editMchtBizDealT.size() > 0){
							for(TblEditMchtBizDeal editMchtBizDealList : editMchtBizDealT){
								baseDao.editSave(editMchtBizDealList);
								logger.info("-----驳回完善T1/T0产品信息成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizDealList.getProdCd()+"[transCd-->"+editMchtBizDealList.getTransCd()+"]-----");
							}
						}
					}
					
					//添加手续费
					if(ConfigMerinfoUtil.T1_FUNCTION.equals(productCode[j]) || ConfigMerinfoUtil.T0_FUNCTION.equals(productCode[j])){ // 银行卡t1/t0
						List<TblEditMchtBizFee> editMchtBizFeeTList = getTblEditMchtBizFeeT(productCode[j], feeList, merinfoTmp.getId(), op, true);
						if(editMchtBizFeeTList != null && editMchtBizFeeTList.size() > 0){
							for(TblEditMchtBizFee editMchtBizFeeT : editMchtBizFeeTList){
								baseDao.editSave(editMchtBizFeeT);
								logger.info("-----驳回完善银行卡T1/T0产品手续费成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizFeeT.getProdCd()+"][SubBizCd-->"+editMchtBizFeeT.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFeeT.getMchtFeePercent()+"]-----");
							}
						}
					}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){	//银联扫码
						if(merinfoTmp.getUpMccCd() != null && merinfoTmp.getUpMccCd().length()>0){ //判断mcc是否选中
							TblEditMchtBizFee tempUionFee = feeList.get(5);
							List<TblEditMchtBizFee> tempUionFees = getUnionAndZwPayFeeList(tempUionFee, merinfoTmp, op, productCode[j], true);
							if(tempUionFees != null && tempUionFees.size() > 0){
								for(TblEditMchtBizFee ubizFee : tempUionFees){
									baseDao.editSave(ubizFee);
									logger.info("-----驳回完善银联扫码手续费成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+ubizFee.getProdCd()+"][SubBizCd-->"+ubizFee.getSubBizCd()+"]-----");
								}
							}
						}
					}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){
						TblEditMchtBizFee tempzwFee = feeList.get(6);
						List<TblEditMchtBizFee> tempzwFees = getUnionAndZwPayFeeList(tempzwFee, merinfoTmp, op, productCode[j], true);
						if(tempzwFees != null && tempzwFees.size() > 0){
							for(TblEditMchtBizFee zbizFee : tempzwFees){
								baseDao.editSave(zbizFee);
								logger.info("-----驳回完善支付宝微信手续费成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+zbizFee.getProdCd()+"][SubBizCd-->"+zbizFee.getSubBizCd()+"]-----");
							}
						}
					}else if(Constant.STR_NUMBER_ONE.equals(merinfoTmp.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j]) ||
							ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){		//直连商户T1/T0手续费
						List<TblEditMchtBizFee> editMchtBizFeeList = getEditMchtBizFeeList(productCode[j], feeList, merinfoTmp.getId(), String.valueOf(op.getId()), true);
						if(editMchtBizFeeList != null && editMchtBizFeeList.size() > 0){
							for(TblEditMchtBizFee editMchtBizFee : editMchtBizFeeList){
								baseDao.editSave(editMchtBizFee);
								logger.info("-----驳回完善直连商户T1/T0手续费成功--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizFee.getProdCd()+"][SubBizCd-->"+editMchtBizFee.getSubBizCd()+"]-----");
							}
						}
					}
				}
				logger.info("-----驳回完善产品开通信息成功-----商户号："+merinfoTmp.getId()+"-----end");
			}else{
				throw new ServiceException(MerinfoReturninfo.S_3.getName());
			}
			/////商户图片
			List<TblEditMchtPicture> pictrueList=merinfoTmp.getPictrueList();
			if(null!=pictrueList && pictrueList.size()>=8){
				//图片信息
				String pic_sql="DELETE FROM TBL_EDIT_MCHT_PICTURE T WHERE T.MCHT_CD=?";
				sqlBaseDao.removeBySql(pic_sql,param);
				logger.info("----删除["+merinfoTmp.getId()+"]图片信息成功-----");
				for (TblEditMchtPicture pi : pictrueList) {
					if(pi.getUrl()==null || pi.getUrl().equals("") || pi.getUrl().length()<1){
						continue;
					}
					TblEditMchtPicture pictrue=new TblEditMchtPicture();
					
					pictrue.setMchtCd(merinfoTmp.getId());//商户号
					pictrue.setUrl(pi.getUrl().trim());//图片地址
					pictrue.setPindex(1);//顺序默认
					
					Random ra=new Random();
					int random=1000+ra.nextInt(8999);
					int first=pi.getUrl().trim().indexOf("mid=")+4;
					int sencond=pi.getUrl().trim().lastIndexOf("&");
					if(first>4 && sencond>0){
						pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
						pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
						pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
					}else{
						String b=pi.getUrl().trim().substring(pi.getUrl().lastIndexOf("&")+1);
						pictrue.setPcode("code");//拆封名称去掉后缀
						pictrue.setFileName(b);//名称
						pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
					}
					pictrue.setDocType("00");
					pictrue.setSystemflag("00");
					pictrue.setStatus("0");
					pictrue.setRecOprId("I");//插入操作
					pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
					pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
					baseDao.editSave(pictrue);
					logger.info("----驳回完善商户图片信息成功--商户号：["+merinfoTmp.getId()+"]图片信息[file_id-->"+pictrue.getFileId()+"]-----");
				}
				logger.info("-----驳回完善商户资料信息成功-----商户号："+merinfoTmp.getId()+"-----end");
			}else{
				throw new ServiceException(MerinfoReturninfo.S_5.getName());
			}
			//商户信息
			String mer_hql=" from TblEditMchtInf t where t.id=?";
			TblEditMchtInf merinfo=(TblEditMchtInf)baseDao.createQueryUniqueResult(mer_hql,param );
			merinfo.setNameBusi(merinfoTmp.getNameBusi());
			merinfo.setName(merinfoTmp.getName());
			merinfo.setProvCd(merinfoTmp.getProvCd());
			merinfo.setCityCd(merinfoTmp.getCityCd());
			merinfo.setAreaCd(merinfoTmp.getAreaCd());
			merinfo.setRegAddr(merinfoTmp.getRegAddr());
			merinfo.setCertif(merinfoTmp.getCertif());
			merinfo.setBusiLiceNo(merinfoTmp.getBusiLiceNo());
			merinfo.setCertifNo(merinfoTmp.getCertifNo());
			merinfo.setCertifType(merinfoTmp.getCertifType());
			merinfo.setContactName(merinfoTmp.getContactName());
			merinfo.setContactPhoneNo(merinfoTmp.getContactPhoneNo());
			merinfo.setBusiMain(merinfoTmp.getBusiMain());
			merinfo.setExt2(merinfoTmp.getExt2()); //备注
			if("3".equals(merRejectFlag)){
				merinfo.setStatus(MerinfoStatus.S_14.getCode());//状态更新为直营进件中
			}else{
				merinfo.setStatus(MerinfoStatus.S_1.getCode());//状态更新为进件中
			}
			merinfo.setRecUpdTs(new Date());//更新当前时间
			merinfo.setMcc(merinfoTmp.getUpMccCd());//mcc
			merinfo.setUpMccCd(merinfoTmp.getUpMccCd());//mcc
			merinfo.setDvpBy(merinfoTmp.getDvpBy()); //是否非法人结算  法人结算1、非法人结算0
			merinfo.setStlmWayDesc(merinfoTmp.getStlmWayDesc());//非法人结算账号
			merinfo.setNationCd(merinfoTmp.getNationCd());//商户类型
			merinfo.setIsGroup(merinfoTmp.getIsGroup());//商户等级
			merinfo.setApprovalUserName(merinfoTmp.getApprovalUserName());
			if(null!=merinfoTmp.getUcBccd() && merinfoTmp.getUcBccd().length()<8){
				merinfo.setUcBccd(op.getOrgCode().substring(0, 4)+merinfoTmp.getUcBccd());
			}else{
				merinfo.setUcBccd(merinfoTmp.getUcBccd());//32域
			}
			 if(merinfo.getUcBccd().trim().length()<5 || merinfo.getUcBccd().trim().indexOf("null")>-1) 
				throw new ServiceException( MerinfoReturninfo.S_27.getName());
			 if(null==merinfoTmp.getGroupCD() ||  merinfoTmp.getGroupCD().trim().length()<1){
					merinfo.setGroupCD(op.getGroupCd()); //商户直连间连选择  默认间连
				}else{
					merinfo.setGroupCD(merinfoTmp.getGroupCD()); //商户直连间连选择
				}
			if("2".equals(merinfoTmp.getGroupCD()) && (Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
					|| Role.OPERATORS_COMM.getCode().equals(op.getRoleType()))){
					merinfo.setBankBelongCd(merinfoTmp.getBankBelongCd());
					merinfo.setExt1(merinfoTmp.getExt1());
					if(Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){
						String ext1 = merinfoTmp.getExt1();
						if(ext1 != null && ext1.length() > 0){
							Operators opr = powerInfoService.loadOperatorsById(Long.valueOf(ext1));
							if(opr != null){
								merinfo.setUcBccdArea(opr.getOneagentid());
							}
						}
					}
				}
			baseDao.editUpdate(merinfo); //商户信息
			logger.info("-----驳回完善商户基本信息成功-----商户号：["+merinfoTmp.getId()+"]---- end");
			merchantDao.addSyslog(SysLogType.MERCHANT_INFO_COMPLETE.getCode(),
					SysLogType.MERCHANT_INFO_COMPLETE.getName(),
					op.getAccountNo(), 
					"操作员【" + op.getAccountNo()+ "】，完善驳回的商户信息【" + merinfo.getId() + "】成功");
			//检查此商户未审核的领件信息，有则删除
			Long rcount = getTReceiveCountInfByMerId(merinfoTmp.getId());
			if(rcount > 0){
				String delrevsql = "DELETE FROM T_RECEIVE T WHERE T.MERNO=? AND T.STATUS = '0' ";
				sqlBaseDao.removeBySql(delrevsql, param);
				logger.info("----删除["+merinfoTmp.getId()+"]商户未审核状态的领件信息成功----");
			}
			logger.info("-----驳回完善商户信息成功-----商户号：["+merinfoTmp.getId()+"]--------------------end");
			return MerinfoReturninfo.S_8.getName();
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException("完善商户信息出错");
		}
	}
	
	@Override
	@Transactional(rollbackFor = { ServiceException.class })
	public String editMerTempSaveInfo(TblEditMchtInf merinfoTmp, Operators op, boolean flag) throws ServiceException {
		String flagName = "";
		logger.info("########[暂存完善商户信息]########"+flagName+"##########start##########商户号：["+merinfoTmp.getId()+"]");
		 try {
			if(flag){
				String str=validateForm(merinfoTmp, op);
				if(null!=str) return str;
				String validateStr=validateCount(merinfoTmp,op);//
				if(null!=validateStr) return validateStr;
				String validate=validateExist(merinfoTmp,op);//校验 身份证  营业执照   银行卡 非法人身份证 是否被风控
				if(null!=validate) return validate; 
				String[] productCode=merinfoTmp.getProductCode();
				if(null == productCode || productCode.length < 1){
					throw new ServiceException(MerinfoReturninfo.S_3.getName());
				}
				List<TblEditMchtPicture> pictrueList=merinfoTmp.getPictrueList();
				if(pictrueList == null || pictrueList.size()<8){
					throw new ServiceException(MerinfoReturninfo.S_5.getName());
				}
				flagName = "提交";
			}else{
				flagName = "保存";
			}
			Object[] param={merinfoTmp.getId()};
			String settle_hql="from TblEditMchtBankAccount t where t.ownerCd=?";
			TblEditMchtBankAccount bankAccount=(TblEditMchtBankAccount)baseDao.createQueryUniqueResult(settle_hql,param );
				String name = merinfoTmp.getBankAccount().getName();
				String account = merinfoTmp.getBankAccount().getAccount();
				String bankName = merinfoTmp.getBankAccount().getBankName();
				String bankCode = merinfoTmp.getBankAccount().getBankCode();
				if(flag){
					if(!("0".equals(name)||"0".equals(account)||"0".equals(bankName)||"0".equals(bankCode))){
						bankAccount.setName(name);
						bankAccount.setAccount(account);
						bankAccount.setBankName(bankName);
						bankAccount.setBankCode(bankCode);
						if(bankCode.length()> 0 &&  !"0".equals(bankCode)){
							bankAccount.setUcBccd(bankCode.substring(0,3));
						}
					}else{
						throw new ServiceException(MerinfoReturninfo.S_46.getName());
					}
				}else{
					if(name.length()<1){
						bankAccount.setName("0");
					}else{
						bankAccount.setName(name);
					}
					if(account.length()<1){
						bankAccount.setAccount("0");
					}else{
						bankAccount.setAccount(account);
					}
					if(bankName.length()<1){
						bankAccount.setBankName("0");
					}else{
						bankAccount.setBankName(bankName);
					}
					if(bankCode.length()<1){
						bankAccount.setBankCode("0");
						bankAccount.setUcBccd("0");
					}else{
						bankAccount.setBankCode(bankCode);
						bankAccount.setUcBccd(bankCode.substring(0,3));
					}
				}
				baseDao.editUpdate(bankAccount);//结算信息
				logger.info("-----[暂存完善商户结算信息成功]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]");
			//商户扩展信息
			TblEditMchtExtendInfo mchtExtendInfo = merinfoTmp.getMchtExtendInfo();
			if("2".equals(op.getGroupCd())){
				String mextend_hql="from TblEditMchtExtendInfo t where t.id=?";
				TblEditMchtExtendInfo mextend=(TblEditMchtExtendInfo)baseDao.createQueryUniqueResult(mextend_hql,param );
				if(mextend != null){
					mextend.setDevelopPerson(mchtExtendInfo.getDevelopPerson());
					mextend.setTermProperty(mchtExtendInfo.getTermProperty());
					mextend.setCertifStartDate(mchtExtendInfo.getCertifStartDate());
					mextend.setCertifEndDate(mchtExtendInfo.getCertifEndDate());
					mextend.setBusiLiceStartDate(mchtExtendInfo.getBusiLiceStartDate());
					mextend.setBusiLiceEndDate(mchtExtendInfo.getBusiLiceEndDate());
					mextend.setBackup5(mchtExtendInfo.getBackup5());
					baseDao.editUpdate(mextend); //商户扩展信息
					logger.info("-----[暂存完善商户扩展信息成功]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]");
				}	
			}
			////终端信息
			List<TblEditTermInf> terminList=merinfoTmp.getTerminfoList();
			if(null!=terminList && terminList.size()>0){
			//删除原终端信息
			String ter_sql="DELETE FROM TBL_EDIT_TERM_INF t WHERE t.MCHT_CD=?";
			int terCount=sqlBaseDao.removeBySql(ter_sql,param);//终端信息
				if(terCount>0){
					logger.info("----删除["+merinfoTmp.getId()+"]下终端成功开始完善----");
					String ter_risk_sql="DELETE FROM  TBL_EDIT_TERM_RISK_CFG t WHERE t.MCHT_CD=?";
					sqlBaseDao.removeBySql(ter_risk_sql,param);//终端风控
					logger.info("----删除["+merinfoTmp.getId()+"]下风控信息成功开始完善----");
				}
				int i=1;
				for (TblEditTermInf tb:terminList) {
					TblEditTermInfId tb_id=new TblEditTermInfId();
					String terId = "";
					if(i<10){
						terId="0000000"+i;
					}else{
						terId="000000"+i;
					}
					tb_id.setMchtCd(merinfoTmp.getId());//商户号
					tb_id.setTermId(terId); //终端号码
					tb.setId(tb_id);
					tb.setBelong("1");
					tb.setBelongSub(String.valueOf(op.getOrgCode()));
					if(flag){
						tb.setStatus("01");//初始状态
					}else{
						tb.setStatus(MerinfoStatus.S_9.getCode());//暂存状态
					}
					tb.setDeviceCd("YJ");//默认sn号码
					tb.setRecCrtTs(new Date());//记录时间
					tb.setDialOut("60000");//终端呼出号码，默认暂定无用处
					tb.setTmnlMoneyIntype("1");//押金收取方式 0按照商户 1按照终端
					baseDao.editSave(tb);
					logger.info("-----[暂存完善商户终端信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]终端号：["+terId+"]");
					//终端风控信息
					TblEditTermRiskCfg ttr=merinfoTmp.getTerminfoRisk();
					if(ttr!=null){//风控信息不为空
						for (int j = 0; j < 2; j++) { //借记卡01、贷记卡 00风控规则
							TblEditTermRiskCfgId  terRiskId=new TblEditTermRiskCfgId();
							if(j==0)//判断卡类型
								terRiskId.setCardType("00");
							else 
								terRiskId.setCardType("01");
							terRiskId.setMchtCd(merinfoTmp.getId());//商户号
							terRiskId.setTermId(terId);//终端号
							TblEditTermRiskCfg terRisk=new TblEditTermRiskCfg();
							terRisk.setId(terRiskId);
							terRisk.setAccpetStartTime(ttr.getAccpetStartTime()); //营业开始时间
							terRisk.setAccpetEndTime(ttr.getAccpetEndTime()); //营业结束时间
							terRisk.setRecCrtTs(new Date());//录入时间
							terRisk.setRecOprId("I");//插入操作标识符
							terRisk.setRecUpdOpr(String.valueOf(op.getId()));//操作员
							terRisk.setOperIn("I");//插入
							baseDao.editSave(terRisk);
							logger.info("-----[暂存完善商户终端风控信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]终端号：["+terId+"]的风控卡类型：["+terRiskId.getCardType()+"]");
						}
					}else{
						throw new ServiceException(MerinfoReturninfo.S_7.getName());
					}
					i++;
				}
			}else{
				throw new ServiceException(MerinfoReturninfo.S_2.getName());
			} 
			////产品信息
			String deal_sql="DELETE FROM  TBL_EDIT_MCHT_BIZ_DEAL t WHERE t.MCHT_CD=?"; //产品信息
			sqlBaseDao.removeBySql(deal_sql,param);
			logger.info("----删除["+merinfoTmp.getId()+"]产品信息成功-----");
			String fees_sql="DELETE FROM TBL_EDIT_MCHT_BIZ_FEE T WHERE T.MCHT_CD=?"; //手续费
			sqlBaseDao.removeBySql(fees_sql,param);
			logger.info("----删除["+merinfoTmp.getId()+"]手续费信息成功-----");
			String[] productCode=merinfoTmp.getProductCode();
			if(null!=productCode && productCode.length>0){
			List<TblEditMchtBizFee> feeList=merinfoTmp.getFee(); //手续费 
			if(null==feeList || feeList.size()<1) return MerinfoReturninfo.S_4.getName();
			//添加产品信息
			for (int j = 0; j < productCode.length; j++) {
				if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){  //银联扫码
					List<TblEditMchtBizDeal> unionpayBizDealList = getUnionpayMchtBizDealList(merinfoTmp, op);
					if(unionpayBizDealList != null && unionpayBizDealList.size() > 0){
						for(TblEditMchtBizDeal ubizDeal : unionpayBizDealList){
							baseDao.editSave(ubizDeal);
							logger.info("-----[暂存完善商户银联扫码产品信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+ubizDeal.getProdCd()+"]");
						}
					}
				}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){  //支付宝微信
					List<TblEditMchtBizDeal> zwpayBizDealList = getZwpayMchtBizDealList(merinfoTmp, op);
					if(zwpayBizDealList != null && zwpayBizDealList.size() > 0){
						for(TblEditMchtBizDeal zbizDeal : zwpayBizDealList){
							baseDao.editSave(zbizDeal);
							logger.info("-----[暂存完善商户支付宝微信产品信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+zbizDeal.getProdCd()+"]");
						}
					}
				}else if(Constant.STR_NUMBER_ONE.equals(merinfoTmp.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j])
						|| ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){  //直连T1/T0产品
					Map<String, String> dproMap=ConfigMerinfoUtil.getDirectProductList(productCode[j], false);
					List<TblEditMchtBizDeal> editMchtBizDealList = getDirectEditMchtBizDealList(dproMap, productCode[j], merinfoTmp.getId(), String.valueOf(op.getId()));
					if(editMchtBizDealList != null && editMchtBizDealList.size()>0){
						for(TblEditMchtBizDeal editMchtBizDeals : editMchtBizDealList){
							baseDao.editSave(editMchtBizDeals);
							logger.info("-----[暂存完善商户直连T1/T0产品信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizDeals.getProdCd()+"]");
						}
					}
				}else{
					Map<String, String> proMap=ConfigMerinfoUtil.getPosFunction(productCode[j], false);	// 银行卡T1/T0产品
					List<TblEditMchtBizDeal> editMchtBizDealT = getEditMchtBizDealTList(proMap, merinfoTmp.getId(), productCode[j], String.valueOf(op.getId()));
					if(editMchtBizDealT != null &&editMchtBizDealT.size() > 0){
						for(TblEditMchtBizDeal editMchtBizDealList : editMchtBizDealT){
							baseDao.editSave(editMchtBizDealList);
							logger.info("-----[暂存完善商户银行卡T1/T0产品信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizDealList.getProdCd()+"[transCd-->"+editMchtBizDealList.getTransCd()+"]");
						}
					}
				}
				//添加手续费
				if(ConfigMerinfoUtil.T1_FUNCTION.equals(productCode[j]) || ConfigMerinfoUtil.T0_FUNCTION.equals(productCode[j])){ // 银行卡t1/t0
					List<TblEditMchtBizFee> editMchtBizFeeTList = getTblEditMchtBizFeeT(productCode[j], feeList, merinfoTmp.getId(), op, flag);
					if(editMchtBizFeeTList != null && editMchtBizFeeTList.size() > 0){
						for(TblEditMchtBizFee editMchtBizFeeT : editMchtBizFeeTList){
							baseDao.editSave(editMchtBizFeeT);
							logger.info("-----[暂存完善商户银行卡T1/T0产品手续费信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码:[prodcd-->"+editMchtBizFeeT.getProdCd()+"][SubBizCd-->"+editMchtBizFeeT.getSubBizCd()+"[MchtFeePercent-->"+editMchtBizFeeT.getMchtFeePercent()+"]");
						}
					}
				}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(productCode[j])){  //银联扫码
					if(merinfoTmp.getUpMccCd() != null && merinfoTmp.getUpMccCd().length()>0){ //判断mcc是否选中
						TblEditMchtBizFee tempUionFee = feeList.get(5);
						List<TblEditMchtBizFee> tempUionFees = getUnionAndZwPayFeeList(tempUionFee, merinfoTmp, op, productCode[j], flag);
						if(tempUionFees != null && tempUionFees.size() > 0){
							for(TblEditMchtBizFee ubizFee : tempUionFees){
								baseDao.editSave(ubizFee);
								logger.info("-----[暂存完善商户银联扫码产品手续费信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+ubizFee.getProdCd()+"][SubBizCd-->"+ubizFee.getSubBizCd()+"]");
							}
						}
					}
				}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(productCode[j])){
					TblEditMchtBizFee tempzwFee = feeList.get(6);
					List<TblEditMchtBizFee> tempzwFees = getUnionAndZwPayFeeList(tempzwFee, merinfoTmp, op, productCode[j], flag);
					if(tempzwFees != null && tempzwFees.size() > 0){
						for(TblEditMchtBizFee zbizFee : tempzwFees){
							baseDao.editSave(zbizFee);
							logger.info("-----[暂存完善商户支付宝微信产品手续费信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+zbizFee.getProdCd()+"][SubBizCd-->"+zbizFee.getSubBizCd()+"]");
						}
					}
				}else if(Constant.STR_NUMBER_ONE.equals(merinfoTmp.getGroupCD()) && (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode[j]) ||
						ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode[j]))){    //直连商户T1/T0手续费
					List<TblEditMchtBizFee> editMchtBizFeeList = getEditMchtBizFeeList(productCode[j], feeList, merinfoTmp.getId(), String.valueOf(op.getId()), flag);
					if(editMchtBizFeeList != null && editMchtBizFeeList.size() > 0){
						for(TblEditMchtBizFee editMchtBizFee : editMchtBizFeeList){
							baseDao.editSave(editMchtBizFee);
							logger.info("-----[暂存完善直连商户T1/T0产品手续费信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]产品码：[prodcd-->"+editMchtBizFee.getProdCd()+"][SubBizCd-->"+editMchtBizFee.getSubBizCd()+"]");
							}
						}
					}
				}
			}
			/////商户图片
			List<TblEditMchtPicture> pictrueList=merinfoTmp.getPictrueList();
			String pic_sql="DELETE FROM TBL_EDIT_MCHT_PICTURE T WHERE T.MCHT_CD=?"; //图片信息
			sqlBaseDao.removeBySql(pic_sql,param);
			logger.info("----删除["+merinfoTmp.getId()+"]图片信息成功-----");
			//商户图片
			if(pictrueList != null){
				List<TblEditMchtPicture> mergPictrueList = mergPictrueListToSave(merinfoTmp, op, flag);
				for(TblEditMchtPicture pictrue : mergPictrueList){
					baseDao.editSave(pictrue);
					logger.info("-----[暂存完善商户图片资料信息]--"+flagName+"--商户号：["+merinfoTmp.getId()+"]图片信息[file_id-->"+pictrue.getFileId()+"]");
				}
			}
			//商户信息
			String mer_hql=" from TblEditMchtInf t where t.id=?";
			TblEditMchtInf merinfo=(TblEditMchtInf)baseDao.createQueryUniqueResult(mer_hql,param );
			merinfo.setNameBusi(merinfoTmp.getNameBusi());
			merinfo.setName(merinfoTmp.getName());
			merinfo.setProvCd(merinfoTmp.getProvCd());
			merinfo.setCityCd(merinfoTmp.getCityCd());
			merinfo.setAreaCd(merinfoTmp.getAreaCd());
			merinfo.setRegAddr(merinfoTmp.getRegAddr());
			merinfo.setCertif(merinfoTmp.getCertif());
			merinfo.setBusiLiceNo(merinfoTmp.getBusiLiceNo());
			merinfo.setCertifNo(merinfoTmp.getCertifNo());
			merinfo.setCertifType(merinfoTmp.getCertifType());
			merinfo.setContactName(merinfoTmp.getContactName());
			merinfo.setContactPhoneNo(merinfoTmp.getContactPhoneNo());
			merinfo.setBusiMain(merinfoTmp.getBusiMain());
			merinfo.setExt2(merinfoTmp.getExt2()); //备注
			if(flag){
				if("2".equals(merinfoTmp.getGroupCD())){
					merinfo.setStatus(MerinfoStatus.S_14.getCode());//状态更新为进件中
				}else{
					merinfo.setStatus(MerinfoStatus.S_1.getCode());//状态更新为进件中
				}
			}else{
				merinfo.setStatus(MerinfoStatus.S_9.getCode());//状态更新为暂存
			}
			merinfo.setRecUpdTs(new Date());//更新当前时间
			merinfo.setMcc(merinfoTmp.getUpMccCd());//mcc
			merinfo.setUpMccCd(merinfoTmp.getUpMccCd());//mcc
			merinfo.setDvpBy(merinfoTmp.getDvpBy()); //是否非法人结算  法人结算1、非法人结算0
			merinfo.setStlmWayDesc(merinfoTmp.getStlmWayDesc());//非法人结算账号
			merinfo.setNationCd(merinfoTmp.getNationCd());//商户类型
			merinfo.setIsGroup(merinfoTmp.getIsGroup());//商户等级
			merinfo.setApprovalUserName(merinfoTmp.getApprovalUserName());
			if(null!=merinfoTmp.getUcBccd() && merinfoTmp.getUcBccd().length()<8){
				merinfo.setUcBccd(op.getOrgCode().substring(0, 4)+merinfoTmp.getUcBccd());
			}else{
				merinfo.setUcBccd(merinfoTmp.getUcBccd());//32域
			}
			if(flag){
				if( merinfo.getUcBccd().trim().length()<5 || merinfo.getUcBccd().trim().indexOf("null")>-1) 
					throw new ServiceException( MerinfoReturninfo.S_27.getName());
			}
			if(null==merinfoTmp.getGroupCD() ||  merinfoTmp.getGroupCD().trim().length()<1){
				merinfo.setGroupCD(op.getGroupCd()); //商户直连间连选择  默认间连
			}else{
				merinfo.setGroupCD(merinfoTmp.getGroupCD()); //商户直连间连选择
			}
			if("2".equals(merinfoTmp.getGroupCD()) && (Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
					|| Role.OPERATORS_COMM.getCode().equals(op.getRoleType()))){
					merinfo.setBankBelongCd(merinfoTmp.getBankBelongCd());
					merinfo.setExt1(merinfoTmp.getExt1());
					if(Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){
						String ext1 = merinfoTmp.getExt1();
						if(ext1 != null && ext1.length() > 0){
							Operators opr = powerInfoService.loadOperatorsById(Long.valueOf(ext1));
							if(opr != null){
								merinfo.setUcBccdArea(opr.getOneagentid());
							}
						}
					}
			}
			baseDao.editUpdate(merinfo); //商户信息
			logger.info("-----[暂存完善商户基本信息成功]--"+flagName+"--商户状态:["+merinfo.getStatus()+"]-----商户号：["+merinfoTmp.getId()+"]");
			merchantDao.addSyslog(SysLogType.MERCHANT_INFO_COMPLETE.getCode(),
					SysLogType.MERCHANT_INFO_COMPLETE.getName(),
					op.getAccountNo(), 
					"操作员【" + op.getAccountNo()+ "】，完善暂存商户信息【" + merinfo.getId() + "】成功");
			logger.info("-----[暂存商户完善商户信息"+flagName+"添加日志成功]-----商户号：["+merinfoTmp.getId()+"]");
			logger.info("########[暂存完善商户信息]########"+flagName+"##########end##########商户号：["+merinfoTmp.getId()+"]");
			return MerinfoReturninfo.S_8.getName();
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
		throw new ServiceException("暂存商户完善"+flagName+"信息出错");
		}
	}
	/**
	 * 查询商户信息详情
	 * @see com.roc.service.IMerchantServices#queryMerinfoDetailInfo(java.lang.String, boolean, java.lang.String)
	 *
	 * @Title: queryMerinfoDetailInfo
	 * @Description:TODO(...)
	 * @param merinfoNo
	 * @param showName
	 * @param rkType
	 * @return
	 * @throws ServiceException
	 * @date: 2018年5月10日 下午4:59:06
	 *
	 */
	@Transactional(readOnly=true)
	public TblMchtInf queryMerinfoDetailInfo(String merinfoNo, boolean showName,String rkType )
			throws ServiceException {
		TblMchtInf mer_info=null;
		 
		 Object[] param={merinfoNo};
		 try {
			if(null==merinfoNo) return mer_info; //为空返回
			
			//商户信息
			String mer_hql=" from TblMchtInf t where t.id=?";
			mer_info=(TblMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
			if(null!=rkType && !rkType.equals("1")){
				String cardNo=mer_info.getCertifNo();//证件号屏蔽
				mer_info.setCertifNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
			}
			
			String phone=mer_info.getContactPhoneNo();//手机号屏蔽
			//mer_info.setContactPhoneNo(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
			mer_info.setContactPhoneNo(phone);
			String k2workflowid =mer_info.getK2WorkFlowId();
			mer_info.setK2WorkFlowId(k2workflowid);
			if(showName){//根据code显示名称
				mer_info.setCertifType(ConfigMerinfoUtil.getCertifType(mer_info.getCertifType()));//证件类型
				mer_info.setProvCd(ConfigMerinfoUtil.getGBProviceName(mer_info.getProvCd()));//省份
				mer_info.setCityCd(ConfigMerinfoUtil.getGBCityName(mer_info.getCityCd()));//城市
				mer_info.setAreaCd(ConfigMerinfoUtil.getGBAreaName(mer_info.getAreaCd()));//地区
				
				//查询进件人员(后期可放入与商户联查，提高页面响应速度)
				String q_sql="SELECT T.REAL_NAME FROM T_OPERATORS T WHERE T.ID=?";
				Object[] params_1={mer_info.getRecUpdOpr()};
				Object op_name=pageDao.findObj(q_sql, params_1);
				mer_info.setRecUpdOpr(String.valueOf(op_name));
			}
			 if(mer_info.getStatus().equals(MerinfoStatus.S_3.getCode())){//需要冻结原因
					String status_hql=" FROM MerinfoStatusChange T WHERE T.status='0' and T.mid=?";
					List<Object> objList=pageDao.queryAll(status_hql, param);
					List<MerinfoStatusChange> changeList=null;
					if(null!= objList && objList.size()>0){
						changeList=new ArrayList<MerinfoStatusChange>();
						for (Object object : objList) {
							MerinfoStatusChange ms=(MerinfoStatusChange)object;
							changeList.add(ms);
						}
						mer_info.setStatusChange(changeList);//冻结原因
					}
				}else if(mer_info.getStatus().equals(MerinfoStatus.S_2.getCode())){//需要注销原因
					String status_hql=" FROM MerinfoStatusChange T WHERE T.status='9' and T.mid=?";
					List<Object> objList=pageDao.queryAll(status_hql, param);
					List<MerinfoStatusChange> changeList=null;
					if(null!= objList && objList.size()>0){
						changeList=new ArrayList<MerinfoStatusChange>();
						for (Object object : objList) {
							MerinfoStatusChange ms=(MerinfoStatusChange)object;
							changeList.add(ms);
						}
						mer_info.setStatusChange(changeList);//注销原因
					}
					
				}
			
			//终端信息
			String ter_hql="from TblTermInf t where t.id.MchtCd=?";
			List<?> objList_ter=pageDao.queryAll(ter_hql, param);
			if(null!=objList_ter && objList_ter.size()>0){
				List<TblTermInf> terList=new ArrayList<TblTermInf>();
				for (Object object : objList_ter) {
					TblTermInf terminfo=(TblTermInf)object;
					if(showName){
						terminfo.setTermTp(ConfigMerinfoUtil.getPosType(terminfo.getTermTp()));//获取终端类型具体名称
					}
					//查询终端风控信息
					String risk_hql="from TblTermRiskCfg t where t.id.MchtCd=? and t.id.TermId=?";
					 Object[] param_risk={merinfoNo,terminfo.getId().getTermId()};
					List<?> objList_risk=pageDao.queryAll(risk_hql, param_risk);
					if(null!=objList_risk && objList_risk.size()>0){
						List<TblTermRiskCfg> riskList=new ArrayList<TblTermRiskCfg>();
						for (Object risk : objList_risk) {
							TblTermRiskCfg fee=(TblTermRiskCfg)risk;
							riskList.add(fee);
						}
						terminfo.setRiskCfgList(riskList); //set 终端风控信息
					}
					terList.add(terminfo);
				}
				mer_info.setTerminfoList(terList);//set终端
				TblTermRiskCfg  tmpTb= new TblTermRiskCfg();
				tmpTb.setAccpetStartTime(terList.get(0).getRiskCfgList().get(0).getAccpetStartTime());
				tmpTb.setAccpetEndTime(terList.get(0).getRiskCfgList().get(0).getAccpetEndTime());
				mer_info.setTerminfoRisk(tmpTb);//获取营业时间
			}
			//产品信息
			String del_hql="select t.prodCd,t.transCd from  TblMchtBizDeal t where t.mchtCd=?";
			List<?> objList_del=pageDao.queryAll(del_hql, param);
			if(null!=objList_del && objList_del.size()>0){
				List<TblMchtBizDeal> delList=new ArrayList<TblMchtBizDeal>();
				String[] produdctArrayStr=new String[objList_del.size()];
				int i=0;
				Iterator<?> iter=objList_del.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblMchtBizDeal terminfo=new TblMchtBizDeal();
					terminfo.setProdCd(String.valueOf(obj[0]));
					terminfo.setTransCd(String.valueOf(obj[1]));
					delList.add(terminfo);
					produdctArrayStr[i]=terminfo.getTransCd();
					i++;
				}
				mer_info.setBizDelList(delList); //产品集合
				mer_info.setProductStrs(produdctArrayStr);//产品
				String[] productCodeStr=queryMchtBizDealArray(merinfoNo, true,showName);
				mer_info.setProductCode(productCodeStr); //保存当前商户所选择的业务模式
			}
			
			//结算信息
			String settle_hql="from TblMchtBankAccount t where t.ownerCd=?";
			TblMchtBankAccount bankAccount=(TblMchtBankAccount)pageDao.createQueryUniqueResult(settle_hql,param );
			//String account=bankAccount.getAccount();
			//bankAccount.setAccount(account.substring(0, 4)+"****"+account.substring(account.length()-4));
			//bankAccount.setAccount(account);
			mer_info.setBankAccount(bankAccount);//SET 结算信息
			
			//手续费
			String fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax,mchtAFeePercent from TblMchtBizFee t where t.mchtCd=? "; 
			List<?> objList_fee=pageDao.queryAll(fees_hql, param);
			String[] productCodedFlag=queryMchtBizDealArray(merinfoNo, true, false);
			if(Constant.STR_NUMBER_ONE.equals(mer_info.getGroupCD()) && 
					(Arrays.asList(productCodedFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
					Arrays.asList(productCodedFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){	//直联商户
				List<TblMchtBizFee> dfeeList = getMerinfoMchtBizFeeList(objList_fee, mer_info, showName);
				mer_info.setFee(dfeeList);
			}else{
				if(null!=objList_fee && objList_fee.size()>0){
					List<TblMchtBizFee> feeList=new ArrayList<TblMchtBizFee>();
					Iterator<?> iter=objList_fee.iterator();
					while(iter.hasNext()){
						Object[] obj=(Object[])iter.next();
						if(!(ConfigMerinfoUtil.ZPAY_FUNCTION_Z.equals(obj[1]) || ConfigMerinfoUtil.WPAY_FUNCTION_Z.equals(obj[1]) 
								|| ConfigMerinfoUtil.WPAY_FUNCTION_F.equals(obj[1]) || "1691".equals(obj[1]))){
							if(obj[3].equals(ConfigMerinfoUtil.T0_2004_FUNCTION) || 
									obj[3].equals(ConfigMerinfoUtil.T0_2005_FUNCTION)){//t0 划付手续费  跳过
									continue;
								}
								TblMchtBizFee fee=new TblMchtBizFee();
								fee.setMchtCd(String.valueOf(obj[0]));
								fee.setProdCd(String.valueOf(obj[1]));
								fee.setBizCd(String.valueOf(obj[2]));
								fee.setSubBizCd(String.valueOf(obj[3]));
								if((obj[4])!=null)
								{
									fee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
								}
								if((obj[5])!=null)
								{
									fee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
								}
								if(showName){
									String name="";
									if(fee.getProdCd().equals(ConfigMerinfoUtil.T1_FUNCTION)){
										name="T1";
									}else if(fee.getProdCd().equals(ConfigMerinfoUtil.T0_FUNCTION)){
										name="T0";
									}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(fee.getProdCd())){
										name = "银联";
									}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(fee.getProdCd())){
										name = "支付宝微信";
									}
									String feeCodeName = ConfigMerinfoUtil.getFeeList(String.valueOf(obj[3])); //根据code 显示手续费名称
									fee.setMchtFeeMd(name + (feeCodeName == null ? "" : feeCodeName)); 
								}
								//D0代付服务费费率
								if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(obj[3]) &&
										null != obj[6] && !(obj[6].toString().trim().equals(""))){
									fee.setMchtAFeePercent(Double.parseDouble(String.valueOf((obj[6]))));
								}
								feeList.add(fee); 
							}
						}
					mer_info.setFee(feeList); //set手续费集合
				}
			}
			
			//图片信息
			String pic_hql="select t.Url,t.DocType  from TblMchtPicture t where t.MchtCd=? and t.DocType<>'SM' order by t.Pcode ASC ";
			List<?> objList_pic=pageDao.queryAll(pic_hql, param);
			if(null!=objList_pic && objList_pic.size()>0){
				List<TblMchtPicture> picList=new ArrayList<TblMchtPicture>();
				Iterator<?> iter=objList_pic.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblMchtPicture picture=new TblMchtPicture();
					picture.setUrl(String.valueOf(obj[0]));
					picList.add(picture); 
				}
				mer_info.setPictrueList(picList);//图片路径地址
			}
			//商户扩展信息
			String extend_hql="from TblMchtExtendInfo t where t.id=?";
			TblMchtExtendInfo tblMchtExtendInfo = (TblMchtExtendInfo)baseDao.createQueryUniqueResult(extend_hql,param );
			if(tblMchtExtendInfo!=null){
				if(StringUtils.isNotEmpty(tblMchtExtendInfo.getDevelopPerson())){
					String operator_hql="from Operators t where t.id=?";
					Object[] paramR={Long.parseLong(tblMchtExtendInfo.getDevelopPerson())};
					Operators operators = (Operators)baseDao.createQueryUniqueResult(operator_hql,paramR);
					if(operators != null){
						tblMchtExtendInfo.setDevelopPersonName(operators.getRealName());
					}
				}
			}
			mer_info.setmExtendInfo(tblMchtExtendInfo);
			return  mer_info;
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException("--查询商户["+merinfoNo+"]详情失败",e);
		}
	}
	
	

	@Transactional(readOnly=true)
	public TblMchtInf queryOtherMerinfoInfo(String merinfoNo,boolean showName,TblMchtInf mer_info)throws ServiceException{
		 
		 Object[] param={merinfoNo};
		 try {
			if(null==merinfoNo) return mer_info; //为空返回
			
			 
				List<TblTermInf> terList=new ArrayList<TblTermInf>();
				List<TblTermInf> objList_ter=mer_info.getTerminfoList();
				for (TblTermInf terminfo : objList_ter) {
					if(showName){
						terminfo.setTermTp(ConfigMerinfoUtil.getPosType(terminfo.getTermTp()));//获取终端类型具体名称
					}
					//查询终端风控信息
					String risk_hql="from TblTermRiskCfg t where t.id.MchtCd=? and t.id.TermId=?";
					 Object[] param_risk={merinfoNo,terminfo.getId().getTermId()};
					List<?> objList_risk=pageDao.queryAll(risk_hql, param_risk);
					if(null!=objList_risk && objList_risk.size()>0){
						List<TblTermRiskCfg> riskList=new ArrayList<TblTermRiskCfg>();
						for (Object risk : objList_risk) {
							TblTermRiskCfg fee=(TblTermRiskCfg)risk;
							riskList.add(fee);
						}
						terminfo.setRiskCfgList(riskList); //set 终端风控信息
					}
					terList.add(terminfo);
					mer_info.setTerminfoList(terList);//set终端
		 		}
 
			
			//结算信息
			String settle_hql="from TblMchtBankAccount t where t.ownerCd=?";
			TblMchtBankAccount bankAccount=(TblMchtBankAccount)pageDao.createQueryUniqueResult(settle_hql,param );
			mer_info.setBankAccount(bankAccount);//SET 结算信息
			
			//手续费
			String fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax from TblMchtBizFee t where t.mchtCd=? order by t.subBizCd asc"; 
			List<?> objList_fee=pageDao.queryAll(fees_hql, param);
			if(null!=objList_fee && objList_fee.size()>0){
				List<TblMchtBizFee> feeList=new ArrayList<TblMchtBizFee>();
				Iterator<?> iter=objList_fee.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					if(obj[3].equals(ConfigMerinfoUtil.T0_2004_FUNCTION) || 
						obj[3].equals(ConfigMerinfoUtil.T0_2005_FUNCTION)){//t0 划付手续费  跳过
						continue;
					}
					TblMchtBizFee fee=new TblMchtBizFee();
					fee.setMchtCd(String.valueOf(obj[0]));
					fee.setProdCd(String.valueOf(obj[1]));
					fee.setBizCd(String.valueOf(obj[2]));
					fee.setSubBizCd(String.valueOf(obj[3]));
					if((obj[4])!=null)
					{
						fee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
					}
					if((obj[5])!=null)
					{
						fee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
					}
					if(showName){
						String name="";
						if(fee.getProdCd().equals(ConfigMerinfoUtil.T1_FUNCTION)){
							name="T1";
						}else if(fee.getProdCd().equals(ConfigMerinfoUtil.T0_FUNCTION)){
							name="T0";
						}
						fee.setMchtFeeMd(name+ConfigMerinfoUtil.getFeeList(String.valueOf(obj[3]))); //根据code 显示名称
					}
					feeList.add(fee); 
				}
				mer_info.setFee(feeList); //set手续费集合
			}
			
			return  mer_info;
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException(e.getMessage(),e);
		}
	
	}

	@Override
	public synchronized List<String> updateTReceiveInfo(Operators op,String merInfoIdList)
			throws ServiceException {
		String sql = "select count(*) from t_receive where merno=? and status='0'";
		String selectSql = "select count(1) from TBL_edit_MCHT_INF where mcht_cd=? and status=?";
		String updateSql = "update TBL_edit_MCHT_INF set status=? where mcht_cd =?";
		
		List<String> cantCollarList = new ArrayList<String>();
		Object[] params =  new Object[1];
		Object[] selectMerchant = new Object[2];
		List<Object> list = new ArrayList<Object>();
		try {
			String[] merinfoIdArray = merInfoIdList.split(",");
			int obj = 0;
			for(int i = 0;i<merinfoIdArray.length;i++){
				logger.info("查询t_receive表中是否有商户号为:"+merinfoIdArray[i]+"的记录，操作员为:"+op.getRealName());
				params[0] = merinfoIdArray[i];
				Object r = sqlBaseDao.findObj(sql, params);
				obj = Integer.parseInt(r.toString());
				if(obj>0){
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				
				selectMerchant[0] = merinfoIdArray[i];
				selectMerchant[1] = MerinfoStatus.S_1.getCode();
				Object c =  sqlBaseDao.findObj(selectSql, selectMerchant);
				logger.info("判断商户表中商户号为"+merinfoIdArray[i]+"的记录的状态是否为领件未审核  c="+c+",操作员为："+op.getRealName());
				if(Integer.parseInt(c.toString())==0){
					logger.info("商户号为 "+merinfoIdArray[i]+" 的商户已被领取");
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				
				list.clear();
				list.add(MerinfoStatus.S_5.getCode());
				list.add(params[0]);
				int updateFlag = sqlBaseDao.deleteBySql(updateSql, list);
				logger.info("更新商户【"+merinfoIdArray[i]+"】的状态，操作员为："+op.getRealName());
				
				if(updateFlag>0){
					TReceive receive = new TReceive();
					receive.setMerNo(merinfoIdArray[i]);
					receive.setOpId(String.valueOf(op.getId()));
					receive.setOpAccountNo(op.getAccountNo());
					receive.setOpAccountName(op.getRealName());
					receive.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					receive.setStatus("0");
					
					logger.info("商户表状态更新成功，开始插入领件表信息,操作员为："+op.getRealName());
					baseDao.editSave(receive);
					logger.info("领件信息插入结束");
					
				}
				
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return cantCollarList;
		
		 
	}
	
	/**
	 * 根据结算卡账户查询已进件数
	 * @param 
	 * */
	@Transactional(readOnly=true)
	public JsonBean queryCountByAccountNo(String accountNo) throws ServiceException {
		String sql="";
		JsonBean jb= new JsonBean();
		//结算卡
		sql="SELECT COUNT(1) FROM TBL_MCHT_BANKACCOUNT T,TBL_MCHT_INF TI WHERE TI.MCHT_CD=T.OWNER_CD AND T.ACCOUNT=? AND TI.STATUS<>'02'";
		/*sql="select (SELECT count(1) FROM TBL_MCHT_BANKACCOUNT T, TBL_MCHT_INF TI WHERE TI.MCHT_CD = T.OWNER_CD"
		    + "  AND T.ACCOUNT = ? AND TI.STATUS <> '02') +"
		    + " (select count(1)  from T_MERINFO_CHANGE mc "
		    +"  where mc.bank_account = ? and mc.deal_code = 'C2' and mc.status='W') cnt from dual";*/
			
		try {
			logger.info("----查询结算卡号 ["+accountNo+"]---");
			Object[] params={accountNo};
			Object r = pageDao.findObj(sql, params);
			Long count = Long.parseLong(r.toString());
			jb.setCode("count");
            jb.setCodeDesc(Long.toString(count));
		} catch (DaoException e) {
			logger.error("-------查询商户结算卡出错-----",e);
			throw new ServiceException("-------查询商户结算卡出错-----",e);
		}
		return jb;
	}
	/**
	 * 根据商户号查询当前结算卡号是否为最新
	 * @param 
	 * */
	@Transactional(readOnly=true)
	public String queryAccountByMer(String merNo) throws ServiceException {
		String sql="";
		JsonBean jb= new JsonBean();
		String accountNo;
		//结算卡
		sql="SELECT t.account FROM TBL_MCHT_BANKACCOUNT T,TBL_MCHT_INF TI WHERE TI.MCHT_CD=T.OWNER_CD AND t.owner_cd=? AND TI.STATUS<>'02'";
			
		try {
			logger.info("----查询商户号 ["+merNo+"]的结算卡号---");
			Object[] params={merNo};
			Object r = pageDao.findObj(sql, params);
			accountNo=r.toString();
		} catch (DaoException e) {
			logger.error("-------查询商户结算卡出错-----",e);
			throw new ServiceException("-------查询商户结算卡出错-----",e);
		}
		return accountNo;
	}
	/**
	 * 根据类别查询在系统已存在多少数量
	 * @param  type 类型
	 * */
	@Transactional(readOnly=true)
	public JsonBean queryCount(String merNo,String type,String obj,Operators op) throws ServiceException {
		JsonBean jb= new JsonBean();
		String sql="";
		String name="";
		if(type.equals("0")){//身份证
			sql="SELECT COUNT(1) FROM TBL_MCHT_INF T WHERE  T.CERTIF_NO=? AND T.STATUS<>'02' and T.CERTIF_NO<>'310109197712243631' "
			 + " AND T.BANK_BELONG_CD='48502000' ";
			name="身份证";
		}else if(type.equals("1")){//营业执照
			sql="SELECT COUNT(1) FROM TBL_MCHT_INF T WHERE  T.BUSI_LICE_NO=? AND T.STATUS<>'02'"
			  + " AND T.BANK_BELONG_CD='48502000'";
			name="营业执照";
		}else if(type.equals("2")){//结算卡
			sql=" SELECT COUNT(1) FROM TBL_MCHT_BANKACCOUNT T,TBL_MCHT_INF TI WHERE TI.MCHT_CD=T.OWNER_CD AND T.ACCOUNT=? AND TI.STATUS<>'02'"
			  + " AND TI.BANK_BELONG_CD='48502000'";
			name="结算卡号";
		}else if(type.equals("3")){//非法人身份证
			sql="SELECT COUNT(1) FROM TBL_MCHT_INF T WHERE  T.STLM_WAY_DESC=? AND T.STATUS<>'02' and T.STLM_WAY_DESC<>'310109197712243631'"
					+ " AND T.BANK_BELONG_CD='48502000'  ";
			name="非法人身份证";
		}
		try {
			logger.info("----审核查询身份证、营业执照、结算卡号类型、非法人身份证 ["+type+"]参数["+obj+"]---");
			Object[] params={obj.trim()};
			Object r = pageDao.findObj(sql, params);
			long count = Long.parseLong(r.toString());
			/************************************--------检测整改---------******************************************/
			sql =" SELECT COUNT(1) FROM TBL_WHITE T WHERE T.STATUS='1' AND T.ACCOUNTNO=? ";
			Object[] accountNo = {op.getAccountNo()};
			Object ra = pageDao.findObj(sql, accountNo);
			long acount = Long.parseLong(ra.toString());
			if(acount<1 && ((type.equals("0") &&  count>2) || (type.equals("1") &&  count>2) 
			 || (type.equals("2") &&  count>1)  || (type.equals("3") &&  count>1))){//身份证
				MerinfoStop stop = new MerinfoStop();
				sql="select COUNT(1) from t_merinfo_stop where mid=? ";
				Object[] par={obj.trim()};
				Object s = pageDao.findObj(sql, par);
				long countNo = Long.parseLong(s.toString());
				if(countNo<1){
					stop.setDetail(name+"在系统中已录入["+count+"]次，请警惕！");  //原因
					if( op.getId()==0){
						stop.setAgentId(40002L);              //添加人员id
					}else{
						stop.setAgentId(op.getId());
					}
					if(null==op.getRealName()){
						stop.setAgentName("cj");
					}else{
						stop.setAgentName(op.getRealName());      //添加人员姓名
					}
					stop.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));  //时间
					stop.setStatus(type);  //类型
					stop.setMid(obj.trim());       //对应号码
					baseDao.editSave(stop);
				}
				jb.setCode("9999");
				jb.setCodeDesc(name+"在系统中已录入["+count+"]次，超出限制，请警惕！");
				
			}else{
				jb.setCode("0000");
				jb.setCodeDesc("");
			} 
			/*********************************************************************************************************/
			/*String whi_sql =" SELECT COUNT(1) FROM t_certif_limt t WHERE t.certif_no=?  ";
			
			Object c = pageDao.findObj(whi_sql, params);
			long whiNo = Long.parseLong(c.toString());
			if(count>9){
				if(whiNo>0){
					jb.setCode("0000");
					jb.setCodeDesc("");
				}else{
					//如果查询结果大于10次  把相关信息存进件限制表中
					MerinfoStop stop = new MerinfoStop();
					sql="select COUNT(1) from t_merinfo_stop where mid=? ";
					Object[] par={obj.trim()};
					Object s = pageDao.findObj(sql, par);
					long countNo = Long.parseLong(s.toString());
					if(countNo<1){
						stop.setDetail(name+"在系统中已录入["+count+"]次，请警惕！");  //原因
						if( op.getId()==0){
							stop.setAgentId(40002L);              //添加人员id
						}else{
							stop.setAgentId(op.getId());
						}
						if( null==op.getRealName())
						{
							stop.setAgentName("cj");
						}else{
							stop.setAgentName(op.getRealName());      //添加人员姓名
						}
						stop.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));  //时间
						stop.setStatus(type);  //类型
						stop.setMid(obj.trim());       //对应号码
						baseDao.editSave(stop);                   
						logger.info("----把身份证、营业执照、结算卡号类型、非法人身份证["+type+"]参数["+obj+"]在系统中存在次数大于规定的加入表t_merinfo_stop---");
					}
					jb.setCode("9999");
					jb.setCodeDesc(name+"在系统中已录入["+count+"]次，超出限制，请警惕！");
				}
			}else{
				jb.setCode("0000");
				jb.setCodeDesc("");
			}*/
		} catch (DaoException e) {
			logger.error("-------审核查询商户结算卡、营业执照、法人身份证出错、非法人身份证-----",e);
			throw new ServiceException("-------审核查询商户结算卡、营业执照、法人身份证出错、非法人身份证-----",e);
		}
		return jb;
	}
	
	/**
	 * 根据类别查询证件在系统中是否被风控
	 * @param  type 类型
	 * */
	@Transactional(readOnly=true)
	public JsonBean queryExist(String merNo,String type,String obj,Operators op) throws ServiceException {
		JsonBean jb=null;
		String sql="";
		sql=" SELECT COUNT(1) FROM T_MERINFO_STOP T WHERE  T.mid=? AND T.mid<>'310109197712243631' ";
		String name="";
		if(type.equals("0")){//身份证
			//sql="SELECT COUNT(1) FROM T_MERINFO_STOP T WHERE  T.mid=? AND STATUS='0' ";
			name="身份证";
		}else if(type.equals("1")){//营业执照
			//sql="SELECT COUNT(1) FROM T_MERINFO_STOP T WHERE  T.mid=? AND STATUS='1' ";
			name="营业执照";
		}else if(type.equals("2")){//结算卡
			//sql="SELECT COUNT(1) FROM T_MERINFO_STOP T WHERE  T.mid=? AND STATUS='2' ";
			name="结算卡号";
		}else if(type.equals("3")){//非法人身份证
			name="非法人身份证";
		}
		try {
			logger.info("----审核查询身份证、营业执照、结算卡号、非法人身份证 是否被限制类型["+type+"]参数["+obj+"]---");
			Object[] params={obj.trim()};
			Object r = pageDao.findObj(sql, params);
			long count = Long.parseLong(r.toString());
			sql =" SELECT COUNT(1) FROM TBL_WHITE T WHERE T.STATUS='1' AND T.ACCOUNTNO=? ";
			Object[] accountNo = {op.getAccountNo()};
			Object ra = pageDao.findObj(sql, accountNo);
			long acount = Long.parseLong(ra.toString());
			if(acount<1 && count>0){
				jb=new JsonBean();
				jb.setCode("9999");
				jb.setCodeDesc(name+"已被风控限制！");
			} 
		} catch (DaoException e) {
			logger.error("-------审核查询商户结算卡、营业执照、法人身份证、非法人身份证是否被风控出错-----",e);
			throw new ServiceException("-------审核查询商户结算卡、营业执照、法人身份证、非法人身份证是否被风控出错-----",e);
			
		}
		return jb;
	}
	
	/**
	 * 根据商户信息校验规则
	 * */
	private String validateForm(TblEditMchtInf merinfo,Operators op)throws ServiceException{
		if(null==op || op.getId()==0 || op.getOrgCode()==null) return MerinfoReturninfo.S_0.getName();
		if(null == merinfo || null==merinfo.getId() || merinfo.getId().trim().length()!=15)return MerinfoReturninfo.S_1.getName();
		//校验32域名
		if(null==merinfo.getUcBccd() || merinfo.getUcBccd().trim().equals(""))  return MerinfoReturninfo.S_27.getName();
		if(merinfo.getUcBccd().trim().length()!=4 || merinfo.getUcBccd().equals("0000")  ){
			return MerinfoReturninfo.S_27.getName();
		}
		if(ConfigMerinfoUtil.getUNProviceName(merinfo.getUcBccd().trim()) == null && ConfigMerinfoUtil.getUNCityName (merinfo.getUcBccd().trim()) == null &&
			  ConfigMerinfoUtil.getUNAreaName (merinfo.getUcBccd().trim()) == null){
			return MerinfoReturninfo.S_27.getName();
		}
		if(null==merinfo.getUpMccCd() || merinfo.getUpMccCd().trim().length()!=4 ) return MerinfoReturninfo.S_28.getName();
		if(null!=merinfo.getApprovalUserName() && merinfo.getApprovalUserName().equals("0")){
			String dvpby=merinfo.getDvpBy();
			if(null!=dvpby && dvpby.equals("1") &&( null==merinfo.getStlmWayDesc() || merinfo.getStlmWayDesc().length()<10)){
				return MerinfoReturninfo.S_36.getName();
			}
			if(dvpby.trim().equals("0") && (!merinfo.getBankAccount().getName().trim().equals(merinfo.getCertif()))){//是法人结算，则名称必须和法人名称一样
				return MerinfoReturninfo.S_37.getName();
			}
		}
		
		//校验国标省份
		if(null==merinfo.getProvCd() || merinfo.getProvCd().trim().length()<4 || ConfigMerinfoUtil.getGBProviceName(merinfo.getProvCd()) == null){
			return MerinfoReturninfo.S_38.getName();
		}
		//校验国标城市
		if(null==merinfo.getCityCd() || merinfo.getCityCd().trim().length()<4 || ConfigMerinfoUtil.getGBCityName(merinfo.getCityCd()) == null){
			return MerinfoReturninfo.S_39.getName();
		}
		//校验国标区县
		if(null==merinfo.getAreaCd() || merinfo.getAreaCd().trim().length()<4 || ConfigMerinfoUtil.getGBAreaName(merinfo.getAreaCd()) == null){
			return MerinfoReturninfo.S_40.getName();
		}
		 
		//校验商户简称
		if(!ConfigMerinfoUtil.isCheckMerName(merinfo.getNameBusi())){
			return MerinfoReturninfo.S_43.getName();
		}
		
		//判断名称是否已存在
		JsonBean json=queryMchtCountByName(null, merinfo.getNameBusi(), true);
		if(null != json && !json.getCode().equals("0000")){
			return MerinfoReturninfo.S_42.getName();
		}
		
		if("2".equals(merinfo.getGroupCD())&& (Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
				|| Role.OPERATORS_LEAD.getCode().equals(op.getRoleType()))){
			String bankBelg = merinfo.getBankBelongCd();
			String ext1 = merinfo.getExt1();
			if(null == bankBelg || bankBelg.trim().equals("")) return MerinfoReturninfo.S_51.getName();
			if(null == ext1 || ext1.trim().equals("")) return MerinfoReturninfo.S_51.getName();
		}
		//判断身份证有效期
		if("2".equals(op.getGroupCd()) && "1".equals(merinfo.getMchtExtendInfo().getCertifValidity())){
			String certStartDate = merinfo.getMchtExtendInfo().getCertifStartDate();
			String certEndDate = merinfo.getMchtExtendInfo().getCertifEndDate();
			if(null == certStartDate || certStartDate.trim().equals("")) return MerinfoReturninfo.S_49.getName();
			if(null == certEndDate || certEndDate.trim().equals("")) return MerinfoReturninfo.S_48.getName();
			if(!ConfigMerinfoUtil.isCheckValidDoc(certStartDate)){
				return MerinfoReturninfo.S_49.getName();
			}
			if(!ConfigMerinfoUtil.isCheckValidDoc(certEndDate)){
				return MerinfoReturninfo.S_48.getName();
			}
		}
		//判断营业执照有效期
		if("2".equals(op.getGroupCd()) && "1".equals(merinfo.getMchtExtendInfo().getBusiLiceValidity())){
			String busiStartDate = merinfo.getMchtExtendInfo().getBusiLiceStartDate();
			String busiEndDate = merinfo.getMchtExtendInfo().getBusiLiceEndDate();
			if(null == busiStartDate || busiStartDate.trim().equals("")) return MerinfoReturninfo.S_47.getName();
			if(null == busiEndDate || busiEndDate.trim().equals("")) return MerinfoReturninfo.S_50.getName();
			if(!ConfigMerinfoUtil.isCheckValidDoc(busiStartDate)){
				return MerinfoReturninfo.S_47.getName();
			}
			if(!ConfigMerinfoUtil.isCheckValidDoc(busiEndDate)){
				return MerinfoReturninfo.S_50.getName();
			}
		}
		return null;
	}
	
	/**
	 * 根据商户信息查询营业执照、身份证、结算卡号是否大于10
	 * */
	private String validateCount(TblEditMchtInf merinfo,Operators op)throws ServiceException{
		try {
			if(merinfo!=null && (null==merinfo.getCertifNo() || merinfo.getCertifNo().trim().equals("") )){
				return MerinfoReturninfo.S_33.getName();
			}
			if(merinfo!=null && (null==merinfo.getBusiLiceNo() || merinfo.getBusiLiceNo().trim().equals("") )){
				return MerinfoReturninfo.S_32.getName();
			}
			
			if(null!=merinfo.getApprovalUserName() && merinfo.getApprovalUserName().equals("0")){//对私账户
				String dvpby=merinfo.getDvpBy();
				if(null!=dvpby && dvpby.equals("1") &&( null==merinfo.getStlmWayDesc() || merinfo.getStlmWayDesc().trim().equals(""))){//非法人结算
					return MerinfoReturninfo.S_36.getName();
				} 
				if(dvpby.trim().equals("0") && (!merinfo.getBankAccount().getName().trim().equals(merinfo.getCertif()))){//是法人结算，则名称必须和法人名称一样
					return MerinfoReturninfo.S_37.getName();
				}
				if(null!=dvpby && dvpby.equals("1") &&  null!=merinfo.getStlmWayDesc()){ //非法人结算，身份证不为空
					JsonBean  jb1=queryCount(null, "3", merinfo.getStlmWayDesc(),op);
					if(null!=jb1 && jb1.getCode().equals("9999")){
						return jb1.getCodeDesc();
					}
				}
			}
			
			JsonBean  jb=queryCount(null, "0", merinfo.getCertifNo(),op);
			if(null!=jb && jb.getCode().equals("9999")){
				return jb.getCodeDesc();
			}
			
			JsonBean  jb1=queryCount(null, "1", merinfo.getBusiLiceNo(),op);
			if(null!=jb1 && jb1.getCode().equals("9999")){
				return jb1.getCodeDesc();
			}
			if(null!=merinfo.getBankAccount()){
				if(merinfo!=null && (null==merinfo.getBankAccount().getAccount() || merinfo.getBankAccount().getAccount().trim().equals("") )){
					return MerinfoReturninfo.S_34.getName();
				}
				if(merinfo.getBankAccount().getAccount().equals("15000037896588")){//公司账户
					return null;
				}
				JsonBean  jb2=queryCount(null, "2", merinfo.getBankAccount().getAccount(),op);
				if(null!=jb2 && jb2.getCode().equals("9999")){
					return jb2.getCodeDesc();
				}
			}
			
		} catch (ServiceException e) {
			throw new ServiceException("校验商户出错",e);
		}
		return null;
	}
	/**
	 * 根据商户信息查询营业执照、身份证、结算卡号是否被限制
	 * @Title: validateExist
	 * @Description: TODO
	 * @param @param merinfo
	 * @param @return
	 * @param @throws ServiceException    
	 * @return String    
	 * @throws
	 */
	@SuppressWarnings("unused")
	private String validateExist(TblEditMchtInf merinfo,Operators op)throws ServiceException{
		try {
			if(merinfo!=null && (null==merinfo.getCertifNo() || merinfo.getCertifNo().trim().equals("") )){
				return MerinfoReturninfo.S_33.getName();
			}
			if(merinfo!=null && (null==merinfo.getBusiLiceNo() || merinfo.getBusiLiceNo().trim().equals("") )){
				return MerinfoReturninfo.S_32.getName();
			}
			
			JsonBean  jb=queryExist(null, "0", merinfo.getCertifNo(), op);
			if(null!=jb && jb.getCode().equals("9999")){
				return jb.getCodeDesc();
			}
			JsonBean  jb1=queryExist(null, "1", merinfo.getBusiLiceNo(), op);
			if(null!=jb1 && jb1.getCode().equals("9999")){
				return jb1.getCodeDesc();
			}
			if(null!=merinfo.getBankAccount()){
				if(merinfo!=null && (null==merinfo.getBankAccount().getAccount() || merinfo.getBankAccount().getAccount().trim().equals("") )){
					return MerinfoReturninfo.S_34.getName();
				}
				if(merinfo.getBankAccount().getAccount().equals("15000037896588")){//公司账户
					return null;
				}
				JsonBean  jb2=queryExist(null, "2", merinfo.getBankAccount().getAccount(), op);
				if(null!=jb2 && jb2.getCode().equals("9999")){
					return jb2.getCodeDesc();
				}
			}
			
			if(null!=merinfo.getApprovalUserName() && merinfo.getApprovalUserName().equals("0")){//对私账户
				String dvpby=merinfo.getDvpBy();
				if(null!=dvpby && dvpby.equals("1") &&( null==merinfo.getStlmWayDesc() || merinfo.getStlmWayDesc().trim().equals(""))){//非法人结算
					return MerinfoReturninfo.S_36.getName();
				}
				if(dvpby.trim().equals("0") && (!merinfo.getBankAccount().getName().trim().equals(merinfo.getCertif()))){//是法人结算，则名称必须和法人名称一样
					return MerinfoReturninfo.S_37.getName();
				}
				if(null!=dvpby && dvpby.equals("1") &&  null!=merinfo.getStlmWayDesc()){ //非法人结算，身份证不为空
					JsonBean  jb3=queryExist(null, "3", merinfo.getStlmWayDesc(), op);
					if(null!=jb3 && jb3.getCode().equals("9999")){
						return jb3.getCodeDesc();
					}
				}
			}
		
			
			
		} catch (ServiceException e) {
			throw new ServiceException("校验商户出错",e);
		}
		return null;
	}
	/**
	 * 根据商户号查询结算周期
	 * @param  mid 商户号
	 * @param  type 是否正式表
	 * @param  showName 是否显示名称
	 * */
	@Transactional(readOnly=true)
	public String[] queryMchtBizDealArray(String mid,boolean type,boolean showName) throws ServiceException {
		String tableName="TBL_EDIT_MCHT_BIZ_DEAL";
		if(type){
			tableName="TBL_MCHT_BIZ_DEAL";
		}
		String sql="SELECT DISTINCT T.PROD_CD FROM "+tableName+" T WHERE T.MCHT_CD=? ORDER BY T.PROD_CD ASC";
		List<String> productArray = new ArrayList<String>();
		try {
			Object[] params={mid};
			List<?> list=pageDao.querySqlAll(sql,params);
			Iterator<?> iter=list.iterator();
			while (iter.hasNext()) {
				Object obj=iter.next();
				if(!showName){
					productArray.add(obj.toString());
				}else{
					if(obj.toString().equals("1000")){
						productArray.add("T1");
					}else if(obj.toString().equals("1171")){
						productArray.add("T0");
					}else if(obj.toString().equals("1191")){
						productArray.add("银联扫码");
					}else if(obj.toString().equals("1391")){
						productArray.add("支付宝微信扫码");
					}else if(obj.toString().equals("1271")){
						productArray.add("直连T0");
					}else if(obj.toString().equals("3000")){
						productArray.add("直连T1");
					}
				}
			}
		} catch (DaoException e) {
			logger.error("----查询商户号["+mid+"]结算周期出错-----",e);
			throw new ServiceException("----查询商户号["+mid+"]结算周期出错-----",e);
		}
		String[] returnStr= (String[])productArray.toArray(new String[productArray.size()]);
		return returnStr;
	}
	
	/**
	 * 根据商户名称查询已经存在的商户
	 * @param mid 商户号
	 * @param  name 商户名称
	 * @param  realTable 是否正式表
	 * */
	@Transactional(readOnly=true)
	public JsonBean queryMchtCountByName(String mid,String name,boolean realTable) throws ServiceException {
		JsonBean jb=new JsonBean();
		try {
			if(null==name) {return jb;}
			String realTableStr="TBL_EDIT_MCHT_INF";
			if(realTable){
				realTableStr="TBL_MCHT_INF";
			}
			String sql="SELECT COUNT(1) FROM "+realTableStr+" T WHERE T.NAME_BUSI=?";
			Object[] params={name.trim()};
			Object r = pageDao.findObj(sql, params);
			long count = Long.parseLong(r.toString());
			logger.info("----根据商户名称["+name+"]查询数量为["+count+"]");
			int resultCount=0;
			if(null!=mid && !mid.equals("")){//变更时有两个
				resultCount=1;
			}
			if(count>resultCount){
				jb.setCode("9999");
				jb.setCodeDesc("该商户名称已经注册过了！");
			}else{
				jb.setCode("0000");
				jb.setCodeDesc("");
			}
		} catch (Exception e) {
			logger.error("----查询商户名称["+name+"]次数出错-----",e);
			throw new ServiceException("----查询商户名称["+name+"]次数出错-----",e);
		}
		return jb;
	}

        /**
         * 根据商户号查询对应的商户下的终端数量
         * @param mid 商户号
         * */
	@Transactional(readOnly=true)
    public JsonBean getMchtNameRealCount(String mid) throws ServiceException {
                JsonBean jb=new JsonBean();
                try {
                        String sql="SELECT COUNT(1) FROM TBL_TERM_INF T WHERE T.MCHT_CD=?";
                        Object[] params={mid.trim()};
                        Object r = pageDao.findObj(sql, params);
                        long count = Long.parseLong(r.toString());
                        logger.info("----根据商户号["+mid+"]查询终端数量为["+count+"]");
                        jb.setCode("count");
                        jb.setCodeDesc(Long.toString(count));
                } catch (Exception e) {
                        logger.error("----查询商户号["+mid+"]对应的终端次数出错-----",e);
                        throw new ServiceException("----查询商户号["+mid+"]终端次数出错-----",e);
                }
                return jb;
        }
/**
 *查询商户变更基本资料(c1,c2)
 */
	@Override
	public MerinfoChangeBean queryMerinfoChangeById(String id) throws ServiceException {
		// TODO Auto-generated method stub
		MerinfoChangeBean merinfo = null;
		List<Object> params=new ArrayList<Object>();
		try {
			StringBuffer sql=new StringBuffer("SELECT TM.ID,TM.MID,TM.NAME_BUSI,TM.CONTACT_PHONE_NO,"
					+ " TM.BANK_ACCOUNT_NAME,TM.OPEN_BANK,TM.BANK_ACCOUNT,TM.BANK_CODE,"
					+ " TM.DEAL_CODE,TM.REMARK,TM.OPERATORS,TM.DT_CREATE_TIME,"
					+ " TM.DT_AUDITOR_TIME,TM.URL1,TM.URL2,TM.URL3,TM.URL4,"
					+ " TM.AGENT_ID,TM.ORG_CODE,TM.STATUS,TM.ACCOUNT_NO "
					+ " from t_merinfo_change  TM "
					+ " WHERE TM.mid=?");
			//String sql="SELECT TM.ID from t_merinfo_change  TM";
			params.add(id);
			List list = merchantDao.queryBySqlToVo(sql.toString(),params.toArray());
		
			if(!list.isEmpty())
			{
				Object[] obj=(Object[]) list.get(0);
				for (Object objs : obj) {
					 merinfo =new MerinfoChangeBean();
					merinfo.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
					merinfo.setMid(Constance.Null2EmptyTrim(obj[1]));
					merinfo.setNameBusi(Constance.Null2EmptyTrim(obj[2]));
					merinfo.setContactPhoneNo(Constance.Null2EmptyTrim(obj[3]));
					merinfo.setBankAccountName(Constance.Null2EmptyTrim(obj[4]));
					merinfo.setOpenBank(Constance.Null2EmptyTrim(obj[5]));
					merinfo.setBankAccount(Constance.Null2EmptyTrim(obj[6]));
					merinfo.setBankCode(Constance.Null2EmptyTrim(obj[7]));
					merinfo.setDealCode(Constance.Null2EmptyTrim(obj[8]));
					merinfo.setRemark(Constance.Null2EmptyTrim(obj[9]));
					merinfo.setOperators(Constance.Null2EmptyTrim(obj[10]));
					//merinfo.setDtAuditorTime(Constance.Null2EmptyTrim(obj[11])));
					//merinfo.setDtAuditorTime(Constance.Null2EmptyTrim(obj[12])));
					merinfo.setUrl1(Constance.Null2EmptyTrim(obj[13]));
					merinfo.setUrl2(Constance.Null2EmptyTrim(obj[14]));
					merinfo.setUrl3(Constance.Null2EmptyTrim(obj[15]));
					merinfo.setUrl4(Constance.Null2EmptyTrim(obj[16]));	
					merinfo.setAgent_id(Long.parseLong(Constance.Null2EmptyTrim(obj[17])));
				//	merinfo.setOrgCode(Constance.Null2EmptyTrim(obj[18]));
					merinfo.setStatus(Constance.Null2EmptyTrim(obj[19]));
					merinfo.setAccNo(Constance.Null2EmptyTrim(obj[20]));
				}
			}
		
		} catch (DaoException e) {
			logger.error("查询商户信息变更失败", e);
			throw new ServiceException("查询商户信息变更失败");
		}
		return merinfo;
	}
	
	@Transactional(readOnly=true)
    public JsonBean queryMchtCountByPhone(String name,boolean realTable) throws ServiceException {
            JsonBean jb=new JsonBean();
            try {
                    String realTableStr="TBL_EDIT_MCHT_INF";
                    if(realTable){
                            realTableStr="TBL_MCHT_INF";
                    }
                    String sql="SELECT COUNT(1) FROM "+realTableStr+" T WHERE T.CONTACT_PHONENO=?";
                    Object[] params={name.trim()};
                    Object r = pageDao.findObj(sql, params);
                    long count = Long.parseLong(r.toString());
                    logger.info("----根据手机号称["+name+"]查询数量为["+count+"]");
                    if(count>5){
                            jb.setCode("9999");
                            jb.setCodeDesc("该手机号不能继续注册！");
                    }else{
                            jb.setCode("0000");
                            jb.setCodeDesc("");
                    }
            } catch (Exception e) {
                    logger.error("----查询手机号称["+name+"]次数出错-----",e);
                    throw new ServiceException("----查询手机号称["+name+"]次数出错-----",e);
            }
            return jb;
    }
	
	/**
	 * 更改商户状态
	 * */
	@Override
	public synchronized JsonBean changeMerinfoStatus(String mid,String type,String account) throws ServiceException {
		JsonBean json=new JsonBean();
		
		String returnInfo="";
		try {
			if(null==mid || null==type) {
				json.setCode("9999");
				json.setCodeDesc(MerinfoReturninfo.S_10.getName());
				return json;
			}
			if( !type.equals(MerinfoStatus.S_0.getCode()) && 
				!type.equals(MerinfoStatus.S_2.getCode()) && 
				!type.equals(MerinfoStatus.S_3.getCode()) ){ 
				
				json.setCode("9999");
				json.setCodeDesc(MerinfoReturninfo.S_11.getName());
				return json;
			}
			String mer_hql=" from TblMchtInf t where t.id=?";
			Object[] param={mid.trim()};
			TblMchtInf mer_info=(TblMchtInf)baseDao.createQueryUniqueResult(mer_hql,param );
			if(null==mer_info){
				json.setCode("9999");
				json.setCodeDesc(MerinfoReturninfo.S_10.getName());
				return json;
			}
			
			if(mer_info.getStatus().equals(type)){ //相同
				json.setCode("9999");
				json.setCodeDesc(MerinfoReturninfo.S_15.getName());
				return json;
			}
			if(mer_info.getStatus().equals(MerinfoStatus.S_2.getCode())){//已经注销
				json.setCode("9999");
				json.setCodeDesc(MerinfoReturninfo.S_16.getName());
				return json;
			}
			if(null!=mer_info.getRecUpdTs()){
				Date dates=mer_info.getRecUpdTs();
				long oldTime=dates.getTime();
				long currentTime=new Date().getTime();
				if(currentTime-oldTime<1000*60*7){
					json.setCode("9999");
					json.setCodeDesc(MerinfoReturninfo.S_14.getName());
					return json;
				}
			}
			mer_info.setStatus(type);
			mer_info.setOperIn("U");
			mer_info.setRecUpdTs(new Date());
			mer_info.setRecOprId("U");
			baseDao.editUpdate(mer_info);
			
			String sysCode="";
			String sysName="";
			if(type.equals(MerinfoStatus.S_0.getCode())){
				returnInfo= MerinfoStatus.S_0.getName();
				sysCode=SysLogType.MERCHANT_OPEN.getCode();
				sysName=SysLogType.MERCHANT_OPEN.getName();
			}else if(type.equals(MerinfoStatus.S_2.getCode())){
				returnInfo= MerinfoStatus.S_2.getName();
				sysCode=SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode();
				sysName=SysLogType.MERINFO_CHANGE_ZHUXIAO.getName();
			}else if(type.equals(MerinfoStatus.S_3.getCode())){
				returnInfo= MerinfoStatus.S_3.getName();
				sysCode=SysLogType.MERCHANT_COLESE.getCode();
				sysName=SysLogType.MERCHANT_COLESE.getName();
			}
			//添加操作日志
			merchantDao.addSyslog(sysCode,sysName,account, 
					"操作员【" + account+ "】，"+returnInfo+"【" + mid + "】成功");
			json.setCode("0000");
			json.setCodeDesc(returnInfo);
		} catch (DaoException e) {
			logger.error("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
			throw new ServiceException("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
		}
		 return json;
	}
	
		/**
         *校验是否可以冻结，解冻，注销
         * */
        @Override
        public synchronized JsonBean changeMerinfoStatusCheck(String mid,String type,String account) throws ServiceException {
                JsonBean json=new JsonBean();
                
                String returnInfo="";
                try {
                        if(null==mid || null==type) {
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_10.getName());
                                return json;
                        }
                        if( !type.equals(MerinfoStatus.S_0.getCode()) && 
                                !type.equals(MerinfoStatus.S_2.getCode()) && 
                                !type.equals(MerinfoStatus.S_3.getCode()) ){ 
                                
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_11.getName());
                                return json;
                        }
                        String mer_hql=" from TblMchtInf t where t.id=?";
                        Object[] param={mid.trim()};
                        TblMchtInf mer_info=(TblMchtInf)baseDao.createQueryUniqueResult(mer_hql,param );
                        if(null==mer_info){
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_10.getName());
                                return json;
                        }
                        
                        if(mer_info.getStatus().equals(type)){ //相同
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_15.getName());
                                return json;
                        }
                        if(mer_info.getStatus().equals(MerinfoStatus.S_2.getCode())){//已经注销
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_16.getName());
                                return json;
                        }
                        if(null!=mer_info.getRecUpdTs()){
                                Date dates=mer_info.getRecUpdTs();
                                long oldTime=dates.getTime();
                                long currentTime=new Date().getTime();
                                if(currentTime-oldTime<1000*60*7){
                                        json.setCode("9999");
                                        json.setCodeDesc(MerinfoReturninfo.S_14.getName());
                                        return json;
                                }
                        }
                        
                        json.setCode("0000");
                        json.setCodeDesc(returnInfo);
                } catch (DaoException e) {
                        logger.error("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
                        throw new ServiceException("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
                }
                 return json;
        }
        /**
         * 更改商户状态2
         * */
        @Override
        public synchronized JsonBean changeMerinfoStatus2(String mid,String type,String account, MerinfoStatusChange merinfoStatusChange) throws ServiceException {
                JsonBean json=new JsonBean();
                
                String returnInfo="";
                try {
                        if(null==mid || null==type) {
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_10.getName());
                                return json;
                        }
                        if( !type.equals(MerinfoStatus.S_0.getCode()) && 
                                !type.equals(MerinfoStatus.S_2.getCode()) && 
                                !type.equals(MerinfoStatus.S_3.getCode()) ){ 
                                
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_11.getName());
                                return json;
                        }
                        String mer_hql=" from TblMchtInf t where t.id=?";
                        Object[] param={mid.trim()};
                        TblMchtInf mer_info=(TblMchtInf)baseDao.createQueryUniqueResult(mer_hql,param );
                        if(null==mer_info){
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_10.getName());
                                return json;
                        }
                        
                        if(mer_info.getStatus().equals(type)){ //相同
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_15.getName());
                                return json;
                        }
                        if(mer_info.getStatus().equals(MerinfoStatus.S_2.getCode())){//已经注销
                                json.setCode("9999");
                                json.setCodeDesc(MerinfoReturninfo.S_16.getName());
                                return json;
                        }
                        if(null!=mer_info.getRecUpdTs()){
                                Date dates=mer_info.getRecUpdTs();
                                long oldTime=dates.getTime();
                                long currentTime=new Date().getTime();
                                if(currentTime-oldTime<1000*60*7){
                                        json.setCode("9999");
                                        json.setCodeDesc(MerinfoReturninfo.S_14.getName());
                                        return json;
                                }
                        }
                        mer_info.setStatus(type);
                        mer_info.setOperIn("U");
                        mer_info.setRecUpdTs(new Date());
                        mer_info.setRecOprId("U");
                        baseDao.editUpdate(mer_info);
                        
                        //保存冻结，解冻，注销 详情
                        baseDao.editSave(merinfoStatusChange);
                        
                        String sysCode="";
                        String sysName="";
                        if(type.equals(MerinfoStatus.S_0.getCode())){
                                returnInfo= MerinfoStatus.S_0.getName();
                                sysCode=SysLogType.MERCHANT_OPEN.getCode();
                                sysName=SysLogType.MERCHANT_OPEN.getName();
                        }else if(type.equals(MerinfoStatus.S_2.getCode())){
                                returnInfo= MerinfoStatus.S_2.getName();
                                sysCode=SysLogType.MERINFO_CHANGE_ZHUXIAO.getCode();
                                sysName=SysLogType.MERINFO_CHANGE_ZHUXIAO.getName();
                                
                                dealwithMerchant(mer_info,account);//注销商户时，删除证件限制表存在的数据。
                                
                        }else if(type.equals(MerinfoStatus.S_3.getCode())){
                                returnInfo= MerinfoStatus.S_3.getName();
                                sysCode=SysLogType.MERCHANT_COLESE.getCode();
                                sysName=SysLogType.MERCHANT_COLESE.getName();
                        }
                        //添加操作日志
                        merchantDao.addSyslog(sysCode,sysName,account, 
                                        "操作员【" + account+ "】，"+returnInfo+"【" + mid + "】成功");
                        json.setCode("0000");
                        json.setCodeDesc(returnInfo);
                        
                } catch (DaoException e) {
                        logger.error("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
                        throw new ServiceException("-----更新商户["+mid+"]状态为["+type+"]失败----",e);
                }
                 return json;
        }
        
        /**
    	 * 注销商户时，删除证件限制表存在的数据
    	 * @param  mer_info 商户
    	 * @param  account 操作员
    	 * @param  
    	 * */
        private void dealwithMerchant(TblMchtInf mer_info,String account) throws ServiceException {
        	int total=0;
        	int obj = 0;
        	String sql="";
        	String sysCode="";
            String sysName="";
            String name="";
        	try {
        		String sqlDel = " delete from t_merinfo_stop t where t.mid=? ";//删除证件限制表数据
        		
        		if(null!=mer_info.getCertifNo() && !"".equals(mer_info.getCertifNo())){
        			name ="法人身份证";
        			sql=" select count(1) from tbl_mcht_inf t,t_merinfo_stop s where  t.certif_no=s.mid and t.certif_no=? ";
        			
        			Object[] param=new Object[1];
        			param[0]=mer_info.getCertifNo();
        			
        			Object object=sqlBaseDao.findObj(sql, param);
        			obj = Integer.parseInt(object.toString());
        			logger.info("查询需要注销的商户【"+mer_info.getId()+"】的法人身份证【"+mer_info.getCertifNo()+"】在证件限制表有"+obj+"条");
        			
        			if(obj>0){
        				total = sqlBaseDao.removeBySql(sqlDel,param);
        				if(total>0){
        					 sysCode=SysLogType.DELETE_STOP_MID.getCode();
                             sysName=SysLogType.DELETE_STOP_MID.getName();
        					merchantDao.addSyslog(sysCode,sysName,account,"操作员【" + account+ "】，注销商户后删除该商户证件限制表"+name+"【" + mer_info.getCertifNo() + "】成功");
        				}
        			}
        		}
        		
        		if(null!=mer_info.getBusiLiceNo() && !"".equals(mer_info.getBusiLiceNo())){
        			name="营业执照";
        			sql = " select count(1) from tbl_mcht_inf t,t_merinfo_stop s where  t.busi_lice_no=s.mid and t.busi_lice_no=? ";
        			
        			Object[] param=new Object[1];
        			param[0]=mer_info.getBusiLiceNo();
        			Object object=sqlBaseDao.findObj(sql, param);
        			obj = Integer.parseInt(object.toString());
        			logger.info("查询需要注销的商户【"+mer_info.getId()+"】的营业执照【"+mer_info.getBusiLiceNo()+"】在证件限制表有"+obj+"条");
        			
        			if(obj>0){
        				total = sqlBaseDao.removeBySql(sqlDel,param);
        				if(total>0){
        					 sysCode=SysLogType.DELETE_STOP_MID.getCode();
                             sysName=SysLogType.DELETE_STOP_MID.getName();
        					merchantDao.addSyslog(sysCode,sysName,account,"操作员【" + account+ "】，注销商户后删除该商户证件限制表"+name+"【" + mer_info.getBusiLiceNo() + "】成功");
        				}
        			}
        		}
        		
        		if(null!=mer_info.getStlmWayDesc() && !"".equals(mer_info.getStlmWayDesc())){
        			name="非法人身份证";
        			sql = " select count(1) from tbl_mcht_inf t,t_merinfo_stop s where  t.stlm_way_desc=s.mid and t.stlm_way_desc=? ";
        			
        			Object[] param=new Object[1];
        			param[0]=mer_info.getStlmWayDesc();
        			Object object=sqlBaseDao.findObj(sql, param);
        			obj = Integer.parseInt(object.toString());
        			logger.info("查询需要注销的商户【"+mer_info.getId()+"】的非法人身份证【"+mer_info.getStlmWayDesc()+"】在证件限制表有"+obj+"条");
        			
        			if(obj>0){
        				total = sqlBaseDao.removeBySql(sqlDel,param);
        				if(total>0){
        					 sysCode=SysLogType.DELETE_STOP_MID.getCode();
                             sysName=SysLogType.DELETE_STOP_MID.getName();
        					merchantDao.addSyslog(sysCode,sysName,account,"操作员【" + account+ "】，注销商户后删除该商户证件限制表"+name+"【" + mer_info.getStlmWayDesc() + "】成功");
        				}
        			}
        		}
        		
        		 String hql=" from TblMchtBankAccount t where t.ownerCd=?";
                 Object[] params={mer_info.getId().trim()};
                 TblMchtBankAccount bankInfo=(TblMchtBankAccount)baseDao.createQueryUniqueResult(hql,params);
                 
        		if(null!=bankInfo.getAccount() && !"".equals(bankInfo.getAccount())){
        			name="结算卡号";
        			sql = " select count(1) from TBL_MCHT_BANKACCOUNT t,t_merinfo_stop s where t.account=s.mid and t.account=? ";
        			
        			Object[] param=new Object[1];
        			param[0]=bankInfo.getAccount();
        			Object object=sqlBaseDao.findObj(sql, param);
        			obj = Integer.parseInt(object.toString());
        			logger.info("查询需要注销的商户【"+mer_info.getId()+"】的结算卡号【"+bankInfo.getAccount()+"】在证件限制表有"+obj+"条");
        			
        			if(obj>0){
        				total = sqlBaseDao.removeBySql(sqlDel,param);
        				if(total>0){
        					 sysCode=SysLogType.DELETE_STOP_MID.getCode();
                             sysName=SysLogType.DELETE_STOP_MID.getName();
        					merchantDao.addSyslog(sysCode,sysName,account,"操作员【" + account+ "】，注销商户后删除该商户证件限制表"+name+"【" + bankInfo.getAccount()+ "】成功");
        				}
        			}
        		}
    			
    		} catch (Exception e) {
    			 logger.error(e.getMessage(),e);
    			 throw new ServiceException(e.getMessage(),e);
    		}
    	
    	}

        
/******************************忘记密码**************************************/	
	/**
         * 根据登录名判断用户是否存在,判断手机号是否正确
         * @param accountNo登录名
         * */
	@Transactional(readOnly=true)
    public JsonBean queryOperatorByAccountNo(String accountNO) throws ServiceException {
                JsonBean jb=new JsonBean();
                try {
                        String sql="SELECT count(1) FROM T_OPERATORS T WHERE T.ACCOUNT_NO=? AND T.ROLE_TYPE <> '17' ";
                        Object[] params={accountNO.trim()};
                        Object r = pageDao.findObj(sql, params);
                        logger.info("----根据登录名称["+accountNO+"]查询数量为["+r.toString()+"]");
                        if(r.toString().equals("0")){
                                jb.setCode("0");
                                jb.setCodeDesc("该登录名不存在");
                        }else if(r.toString().equals("1")){
                                //该用户存在的时候查询手机号
                                String sqlMobile="SELECT MOBILE FROM T_OPERATORS T WHERE T.ACCOUNT_NO=?";
                                Object[] paramsmobile={accountNO.trim()};
                                Object m = pageDao.findObj(sqlMobile, paramsmobile);
                                String mobile = (String) m;
                                
                                Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); 
                                Matcher mb = p.matcher(mobile);
                                if(!mb.matches()){
                                    jb.setCode("0");
                                    jb.setCodeDesc("该用户"+accountNO+"存在,输入的手机号不匹配");
                                }else{
                                    jb.setCode("1");
                                    jb.setCodeDesc("该用户"+accountNO+"存在");
                                }
                        }
                } catch (Exception e) {
                        logger.error("----查询登录名["+accountNO+"]是否存在出错-----",e);
                        throw new ServiceException("----查询登录名["+accountNO+"]是否存在出错-----",e);
                }
                return jb;
        }
        
        /**
         * 根据登录名查询用户的手机号
         * @param accountNo登录名
         * */
		@Transactional(readOnly=true)
        public String queryPhoneByAccountNo(String accountNO) throws ServiceException {
                String mobile;
                try {
                        String sql="SELECT MOBILE FROM T_OPERATORS T WHERE T.ACCOUNT_NO=? AND T.ROLE_TYPE <> '17' ";
                        Object[] params={accountNO.trim()};
                        Object r = pageDao.findObj(sql, params);
                        mobile = (String) r;
                        
                } catch (Exception e) {
                        logger.error("----查询登录名["+accountNO+"]手机号出错-----",e);
                        throw new ServiceException("----查询登录名["+accountNO+"]是手机号出错-----",e);
                }
                return mobile;
        }
        /**
         * 修改密码发送短信验证码
         * 
         */
        @Override
        public JsonBean sendMsg(String accountNO,String verifyCode) throws ServiceException {
                JsonBean jb=new JsonBean();
                try {
                	     //查询当前账号的手机号
                	     String sql="SELECT MOBILE FROM T_OPERATORS T WHERE T.ACCOUNT_NO=?";
                         Object[] params={accountNO.trim()};
                         Object r = pageDao.findObj(sql, params);
                        String mobile = (String) r;
                        
                        String msg = "验证码:"+ verifyCode +",付临门用户,您正在通过手机找回密码操作[验证码告知他人将导致账号被盗，请勿泄露]" ;
                  
                        
                        logger.info("开始发送验证码，发送号码为：" + mobile + ",发送的验证码为："+ verifyCode);
                        
                        //发短信
                        //String url = "http://188.68.88.102:7004/dypay/sendMSGAction.action";
                        String url = Utils.getConfigValue("DD_SSM");
                        StringBuffer pmes = new StringBuffer();
                        pmes.append("mobileNo=").append(mobile).append("&sendMsg=").append(msg);
                        
                        try {
                            HttpUtil.sendGetOrPost(url, pmes.toString());
                            logger.info("发送参数："+pmes);
                            
                            logger.info("修改信息表数据开始");

                            MessageSend messSend = new MessageSend();
                            messSend.setPhoneNumber(mobile);
                            messSend.setMesContent(msg);
                            messSend.setSendFlag("1");
                            Date date = new Date();
                            messSend.setDtCreate(date);
                            messSend.setDtLastmod(date);
                            baseDao.editSave(messSend);
                            
                            jb.setCode("1");
                            jb.setCodeDesc("发送验证码成功");
//                            jb.setCodeDesc(mobile.substring(0, 3)+"****"+mobile.substring(7));
                            
                        } catch (Exception e) {
                            jb.setCode("0");
                            jb.setCodeDesc("发送验证码失败,请重新发送");
//                            jb.setCodeDesc(mobile.substring(0, 3)+"****"+mobile.substring(7));
                        }
                        
                } catch (Exception e) {
                        logger.error("----["+accountNO+"]找回密码发送短信验证码出错-----",e);
                        throw new ServiceException("----["+accountNO+"]找回密码发送短信验证码出错------",e);
                }
                return jb;
        }
        
        

	public static void main(String[] args) {
		/*	String a="/upload/11012013/101301039980000/1013010399800000201.jpg";
			String b=a.substring(a.lastIndexOf("/")+1);
			String e="8884213411100000101";
			String c="8884213411123450156";
			System.out.println(c.substring(15,17));*/
			/*System.out.println(b);
			System.out.println(b.substring(0,b.indexOf(".")));*/
		//发短信
        /*String url = "http://localhost:9090/CheckFileProjects/sendDDS";
        StringBuffer pmes = new StringBuffer();
        pmes.append("mobile=").append("18116219710").append("&content=").append("1111");
        
        try {
            HttpUtil.sendGetOrPost(url, pmes.toString());
        }catch(Exception e){
        	
        }*/
		}
	   /**
     * 保存商户变更信息领件serviceimpl
     */
	@Override
	public  List<String> queryTChangeReceiveChange(Operators op,String merInfoIdList)
				throws ServiceException {
			/*Object[] params =  new Object[1];
			params[0] = merinfo.getId();
			
			Object[] selectMerchant = new Object[2];*/
			
			String sql = "select count(*) from t_change_receive where merno=? and status='0'";
			String updateSql = "update T_MERINFO_CHANGE set status='L' where mid =? AND status='W'";
			String selectSql = "select count(1) from T_MERINFO_CHANGE where mid=? and status=?";
			/*int obj = 0;*/
			List<String> cantCollarList = new ArrayList<String>();
			Object[] params =  new Object[1];
			Object[] selectMerchant = new Object[2];
			List<Object> list = new ArrayList<Object>();
			try {
				String[] merinfoIdArray = merInfoIdList.split(",");
				int obj = 0;
				for(int i = 0;i<merinfoIdArray.length;i++){
					logger.info("查询t_receive表中是否有商户号为:"+merinfoIdArray[i]+"的记录，操作员为:"+op.getRealName());
					params[0] = merinfoIdArray[i];
					Object r = sqlBaseDao.findObj(sql, params);
					obj = Integer.parseInt(r.toString());
					if(obj>0){
						cantCollarList.add(merinfoIdArray[i]);
						continue;
					}
					
					selectMerchant[0] = merinfoIdArray[i];
					selectMerchant[1] = "L";
					Object c =  sqlBaseDao.findObj(selectSql, selectMerchant);
					logger.info("判断商户表中商户号为"+merinfoIdArray[i]+"的记录的状态是否为领件未审核  c="+c+",操作员为："+op.getRealName());
					if(Integer.parseInt(c.toString())>0){
						logger.info("商户号为 "+merinfoIdArray[i]+" 的商户已被领取");
						cantCollarList.add(merinfoIdArray[i]);
						continue;
					}
					list.clear();
					list.add(params[0]);
					//int updateFlag = merinfoChangeCheckDao.updateBySql(updateSql.toString(), list.toArray());
					int updateFlag = sqlBaseDao.deleteBySql(updateSql, list);
					logger.info("更新商户【"+merinfoIdArray[i]+"】的状态，操作员为："+op.getRealName());
					
					if(updateFlag>0){
						TChangeReceive receive = new TChangeReceive();
						receive.setMerNo(merinfoIdArray[i]);
						receive.setOpId(String.valueOf(op.getId()));
						receive.setOpAccountNo(op.getAccountNo());
						receive.setOpAccountName(op.getRealName());
						receive.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
						receive.setStatus("0");
						
						logger.info("商户表状态更新成功，开始插入领件表信息,操作员为："+op.getRealName());
						baseDao.editSave(receive);
						logger.info("领件信息插入结束");
						
					}
					
				}
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				throw new ServiceException(e.getMessage(),e);
			}
			return cantCollarList;
	}

	 
	@Transactional(readOnly=true)
	public TblMchtInf queryMerinfoInfoById(String merinfoNo)
			throws ServiceException {
		TblMchtInf merinfo=null;
		Object[] param={merinfoNo};
		try {
			if(null==merinfoNo) return  merinfo; //为空返回
			//商户信息
			String mer_hql=" from TblMchtInf t where t.id=?";
			merinfo=(TblMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
			String  pro=ConfigMerinfoUtil.getGBProviceName(merinfo.getProvCd());
			String  city=ConfigMerinfoUtil.getGBCityName(merinfo.getCityCd());
			String  area=ConfigMerinfoUtil.getGBAreaName(merinfo.getAreaCd());
			merinfo.setProvCd(pro);//省份
			merinfo.setCityCd(city);//城市
			merinfo.setAreaCd(area);//地区
			//结算信息
			String settle_hql="from TblMchtBankAccount t where t.ownerCd=?";
			TblMchtBankAccount bankAccount=(TblMchtBankAccount)pageDao.createQueryUniqueResult(settle_hql,param );
			merinfo.setBankAccount(bankAccount);//SET 结算信息					
			return  merinfo;
			} catch (DaoException e) {
			 	logger.error(e.getMessage(),e);
			 	throw new ServiceException(e.getMessage(),e);
			}
	}
	
	/**
	 * 商户释放
	 */
	
	@Override
	public synchronized List<String> merinfoRelease(Operators op,String merInfoIdList)
			throws ServiceException {
		String sql = "select count(*) from t_receive where merno=? and status='0'";
		String updateSql = "update TBL_edit_MCHT_INF set status=? where mcht_cd =?";
	    String update_tr ="update t_receive set status=? where merno=? and status='0' ";
		String selectSql = "select count(1) from TBL_edit_MCHT_INF where mcht_cd=? and status=?";
		List<String> cantCollarList = new ArrayList<String>();
		Object[] params =  new Object[1];
		Object[] selectMerchant = new Object[2];
		List<Object> list = new ArrayList<Object>();
		try {
			String[] merinfoIdArray = merInfoIdList.split(",");
			int obj = 0;
			for(int i = 0;i<merinfoIdArray.length;i++){
				logger.info("查询t_receive表中是否有商户号为:"+merinfoIdArray[i]+"的记录，操作员为:"+op.getRealName());
				params[0] = merinfoIdArray[i];
				Object r = sqlBaseDao.findObj(sql, params);
				obj = Integer.parseInt(r.toString());
				if(obj<=0){
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				
				selectMerchant[0] = merinfoIdArray[i];
				selectMerchant[1] = MerinfoStatus.S_5.getCode();
				Object c =  sqlBaseDao.findObj(selectSql, selectMerchant);
				logger.info("判断商户表中商户号为"+merinfoIdArray[i]+"的记录的状态是否为领件未审核  c="+c+",操作员为："+op.getRealName());
				if(Integer.parseInt(c.toString())<=0){
					logger.info("商户号为 "+merinfoIdArray[i]+" 的商户没被领取");
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				
				list.clear();
				list.add(MerinfoStatus.S_1.getCode());
				list.add(params[0]);
				int updateFlag = sqlBaseDao.deleteBySql(updateSql, list);
				logger.info("更新商户【"+merinfoIdArray[i]+"】的状态，操作员为："+op.getRealName());
				
				list.clear();
				list.add('1');
				list.add(params[0]);
				int ss = sqlBaseDao.deleteBySql(update_tr, list);
				logger.info("变更零件表中商户【"+merinfoIdArray[i]+"】的状态，操作员为："+op.getRealName());
				
				/*if(updateFlag>0){
					TReceive receive = new TReceive();
					receive.setMerNo(merinfoIdArray[i]);
					receive.setOpId(String.valueOf(op.getId()));
					receive.setOpAccountNo(op.getAccountNo());
					receive.setOpAccountName(op.getRealName());
					receive.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					receive.setStatus("0");*/
					
					//logger.info("商户表状态更新成功，开始插入领件表信息,操作员为："+op.getRealName());
				//	baseDao.editSave(receive);
					logger.info("商户释放成功");
					
			
				
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return cantCollarList;
    }
	/**
	 * 商户分配
	 */

	@SuppressWarnings("null")
	@Override
	public synchronized Map<String,Object> merinfoAlloat(MerinfoAlloatSearchCondtion alloatOp,Operators op,String merInfoIdList)
			throws ServiceException {
		String sql = "select count(*) from t_receive where merno=? and status='0'";
		String select_op= " SELECT ID,ACCOUNT_NO, REAL_NAME FROM T_OPERATORS  WHERE REAL_NAME=? AND STATUS='00' and ( role_type='12' OR  role_type='13') ";
	    String update_tr ="update t_receive set OP_ID=?,OP_ACCOUNTNO=?,OP_ACCOUNTNAME=?,CREATEDATE=? where merno=? and status='0' ";
		String selectSql = "select count(1) from TBL_edit_MCHT_INF where mcht_cd=? and status=?";
		List<String> cantCollarList = new ArrayList<String>();
		Object[] params =  new Object[1];
		Object[] selectMerchant = new Object[2];
		List<Object> list = new ArrayList<Object>();
		Map<String,Object> map = new HashMap<String,Object>(); 
		try {
			String[] merinfoIdArray = merInfoIdList.split(",");
			int obj = 0;
			for(int i = 0;i<merinfoIdArray.length;i++){
				logger.info("查询t_receive表中是否有商户号为:"+merinfoIdArray[i]+"的被领件记录，操作员为:"+op.getRealName());
				params[0] = merinfoIdArray[i];
				Object r = sqlBaseDao.findObj(sql, params);
				obj = Integer.parseInt(r.toString());
				if(obj<=0){
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				selectMerchant[0] = merinfoIdArray[i];
				selectMerchant[1] = MerinfoStatus.S_5.getCode();
				Object c =  sqlBaseDao.findObj(selectSql, selectMerchant);
				logger.info("判断商户表中商户号为"+merinfoIdArray[i]+"的记录的状态是否为领件未审核  c="+c+",操作员为："+op.getRealName());
				if(Integer.parseInt(c.toString())<=0){
					logger.info("商户号为 "+merinfoIdArray[i]+" 的商户没被领取");
					cantCollarList.add(merinfoIdArray[i]);
					continue;
				}
				logger.info("查询t_OPERATORS表中是否有姓名为:"+alloatOp.getAlloatName()+"的记录，操作员为:"+op.getRealName());
				params[0] = alloatOp.getAlloatName();
				Object cc=sqlBaseDao.findObj(select_op, params);
				if(null != cc){
					for(int x=0;x<merinfoIdArray.length;x++) {
				
					Object[] c1=(Object[]) cc;
					list.add(Constance.Null2EmptyTrim(c1[0]));    //分配人员id
					list.add(Constance.Null2EmptyTrim(c1[1]));   //分配人员账号
					list.add(Constance.Null2EmptyTrim(c1[2]));   //分配人员姓名
					list.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //创建时间
					list.add(merinfoIdArray[x]); 
					sqlBaseDao.deleteBySql(update_tr, list);
					list.clear();
					logger.info("变更领件表中商户【"+merinfoIdArray[i]+"】的状态，操作员为："+op.getRealName());
					logger.info("分配商户：【"+merinfoIdArray[i]+"】的给【"+alloatOp.getAlloatName()+"】，操作员为："+op.getRealName());
					}
					logger.info("分配成功");
					map.put("success", list);//分配成功信息  
				}else{ //查询风控人员不存在
					
					logger.info("请选择分配风控人员！");
					map.put("error", "请选择分配风控人员！");
				}
	
	
	
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return map;
    }
	
	@Override
	public List<Operators> getSubAgent(Operators op) throws ServiceException {
		String subSql="SELECT ID,REAL_NAME FROM T_OPERATORS T WHERE T.ROLE_TYPE=? START WITH T.ID=? CONNECT BY PRIOR  T.ID= T.SUPRI_ID ORDER BY LEVEL";
		Object[] parmas=new Object[2];
		parmas[0]=Role.AGENT.getCode();
		parmas[1]=op.getId();
		List<Operators> listAgent=new ArrayList<Operators>();
		try {
			List<Object> list=sqlBaseDao.queryAll(subSql, parmas);
			if(list!=null && list.size()>0){
				for(int i=0;i<list.size();i++)
				{
					Object[] obj=(Object[]) list.get(i);
					Operators subOp=new Operators();
					subOp.setId(Long.parseLong(String.valueOf(obj[0])));
					subOp.setRealName(String.valueOf(obj[1]));
					listAgent.add(subOp);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return listAgent;
	}
	/**
	 * 确保同一商户同一时刻只准许一个代理商分配
	 */
	@Override
	@Transactional(rollbackFor = { ServiceException.class })
	public synchronized Map<String, Object> assginMerchtToAgent(String mchtId,String oldAgentId,String newAgentId,Operators op)
			throws ServiceException {
		Map<String, Object> map=new HashMap<String, Object>();
		String updateMchtSql="UPDATE TBL_MCHT_INF SET EXT1=? WHERE MCHT_CD=? AND EXT1=?";//修改商户表
		String sql="SELECT S.MERNO,S.MERNAME FROM TBL_MER_AGENT_RELATION S WHERE S.AGENTID=? AND S.MERNO=?";//获取原始完整的信息
		String deleteSql="DELETE FROM TBL_MER_AGENT_RELATION  S WHERE S.MERNO=?";//剔除原始商户代理商关系
		String insertSql="INSERT INTO tbl_change_agent_direct VALUES(?,?,?,SYSTIMESTAMP)";
		String updateSql="UPDATE TBL_CHANGE_AGENT_DIRECT SET ORIGIN_AGENT_ID=?,OPERATORS_ID=?,CHANGE_DATE=SYSTIMESTAMP WHERE MCHT_CD=?";
		try {
		//首先检验是否存在数据
		String msg=null;
		logger.info("首先检验是否存在数据,并获取原始商户数据");
		Object[] viParams=new Object[2];
		viParams[0]=Long.parseLong(oldAgentId);
		viParams[1]=mchtId;
		Object object=sqlBaseDao.findObj(sql,viParams);
		Object[] mchtObj=(Object[]) object;
		if(object==null){
			msg="商户代理商关系表中不存在该条数据";
			logger.info("msg");
			map.put("result", msg);
			return map;
		}
		//更改商户表
		List<Object> parmasMcht=new ArrayList<Object>();
		parmasMcht.add(newAgentId);
		parmasMcht.add(mchtId);
		parmasMcht.add(oldAgentId);
		int count=sqlBaseDao.deleteBySql(updateMchtSql, parmasMcht);
		if(count>0){
			logger.info("更新商户表成功~");
			//向中间表插入或更新原代理商ID
			List<Object> parmasTemp=new ArrayList<Object>();
			parmasTemp.add(Long.parseLong(oldAgentId));
			parmasTemp.add(op.getId());
			parmasTemp.add(mchtId);
			count = sqlBaseDao.deleteBySql(updateSql, parmasTemp);
			if(count==0){
				parmasTemp.clear();
				parmasTemp.add(mchtId);
				parmasTemp.add(Long.parseLong(oldAgentId));
				parmasTemp.add(op.getId());
				count=sqlBaseDao.deleteBySql(insertSql, parmasTemp);
				if(count>0){
					logger.info("成功保存原始所属代理商~");
				}else{
					throw new ServiceException("保存原始所属代理商失败~");
				}
			}else if(count>0){
				logger.info("成功修改原始所属代理商~");
			}
			//剔除原始商户代理商关系
			List<Object> parmas=new ArrayList<Object>();
			parmas.add(mchtId);
			count=sqlBaseDao.deleteBySql(deleteSql, parmas);
			if(count>0){
				logger.info("成功从商户代理商关系表中清除原始关系~");
				logger.info("重新建立商户代理商关系~");
				long a=merchantDao.addMerinfoAgentRelations(String.valueOf(mchtObj[0]), String.valueOf(mchtObj[1]), Long.parseLong(String.valueOf(newAgentId)));
				if(a>0){
					logger.info("----添加代理商商户关系成功共计["+a+"]个上级--------");
					return map;
					}else{
						throw new ServiceException("重新建立商户代理商关系失败~");
					}
				}else{
					throw new ServiceException("清除商户代理商关系失败~");
				}
			}else{
				throw new ServiceException("更新商户所属代理商失败~");
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}		
	}

	@Override
	public Operators findOldAgent(String mchtId) throws ServiceException {
		String oldSql="SELECT T.ID,T.REAL_NAME FROM TBL_MCHT_INF S,T_OPERATORS T WHERE T.ID=TO_NUMBER(S.EXT1) AND S.MCHT_CD=?";
		Object[] params=new Object[1];
		params[0]=mchtId;
		Operators op=null;
		try {
			Object object=sqlBaseDao.findObj(oldSql, params);
			if(object!=null)
			{
				Object[] obj=(Object[]) object;
				op=new Operators();
				op.setId(Long.parseLong(String.valueOf(obj[0])));
				op.setRealName(String.valueOf(obj[1]));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return op;
	}
	/**
	 * 批量修改商户状态
	 * @param midList
	 * @param type 0-冻结，1-解冻，2-注销，3-开通
	 * @param account
	 * @return
	 * @throws ServiceException
	 */
	@Override
	public List<String> changeMerinfoStatusBanch(List<List<String>> midList,
			String type, String account) throws ServiceException {
		StringBuffer misStr = new StringBuffer();
		List<String> list = new ArrayList<String>();
		for(int i=1;i<midList.size();i++){
			misStr.append(midList.get(i).get(0)+"@"+midList.get(i).get(1)).append("#");
		}
		try{
			list = merchantDao.updateMerStatusBanch(misStr.toString(),type,account);
		}catch(DaoException e){
			logger.error(e.getMessage(),e);
			throw new ServiceException(e.getMessage(),e);
		}
		return list;
	}

	/**
	 * 商户审核通过-获取商户开通的产品类型信息(移除t1 t0)
	 * @param mid
	 * @return
	 * @throws ServiceException
	 */
	public List<String> queryMchtBizDealChecked(String mid) throws ServiceException {
		String sql="SELECT DISTINCT T.PROD_CD FROM TBL_EDIT_MCHT_BIZ_DEAL T WHERE T.MCHT_CD=? ORDER BY T.PROD_CD ASC";
		List<String> productCheckedList = new ArrayList<String>();
		try {
			Object[] params={mid};
			List<?> list=pageDao.querySqlAll(sql,params);
			Iterator<?> iter=list.iterator();
			while (iter.hasNext()) {
				Object obj=iter.next();
				productCheckedList.add(obj.toString());
			}
			for(int i = 0; i < productCheckedList.size(); i++){	//移除t1 t0产品类型
				String s = productCheckedList.get(i);
				if(ConfigMerinfoUtil.T1_FUNCTION.equals(s) || ConfigMerinfoUtil.T0_FUNCTION.equals(s)){
					productCheckedList.remove(s);
					i--;
				}
			}
		} catch (DaoException e) {
			logger.error("----商户审核--查询商户号["+mid+"]开通的产品类型信息出错-----",e);
			throw new ServiceException("----商户审核--查询商户号["+mid+"]开通的产品类型信息出错-----",e);
		}
		return productCheckedList;
	}

	@Override
	public Operators queryOperByRoleAndOrg(String roleType, String orgCode)
			throws ServiceException {
		Operators oper = null;
		try{
			oper = merchantDao.queryOperByRoleAndOrg(roleType, orgCode);
		}catch(DaoException e){
			logger.error("查询机构"+orgCode+"管理员不唯一");
			throw new ServiceException("查询机构"+orgCode+"管理员不唯一",e);
		}
		return oper;
	}

	@Override
	public List<Operators> queryAllOneAgent(String companyid) throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		
		String sql = "SELECT id,account_no,real_name,oneagentid FROM t_operators t where  t.role_type = '02' and t.companyid = " + companyid;
		try {
			objList = sqlBaseDao.queryAll(sql);
			if (objList != null && objList.size() > 0) {
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchant.setOneagentid((String) obj[3]);
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}
	
	/**
	 * 获取临时表银联扫码产品列表
	 * @param merinfo
	 * @param op
	 * @return
	 */
	public List<TblEditMchtBizDeal> getUnionpayMchtBizDealList(TblEditMchtInf merinfo, Operators op){
		List<TblEditMchtBizDeal> unionpayBizDealList = new ArrayList<TblEditMchtBizDeal>();
		for(int i = 0;i < 4;i++){
			TblEditMchtBizDeal tmbUnionpayPro = new TblEditMchtBizDeal();
			tmbUnionpayPro.setMchtCd(merinfo.getId());
			tmbUnionpayPro.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
			tmbUnionpayPro.setOperIn("I");
			tmbUnionpayPro.setRecUpdOpr(String.valueOf(op.getId()));
			tmbUnionpayPro.setRecCrtTs(new Date());
			if(i == 0){
				tmbUnionpayPro.setTransCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION); //银联扫码正扫-开通
				tmbUnionpayPro.setProdCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION);
			}else if(i == 1){
				tmbUnionpayPro.setTransCd("1161"); //银联扫码正扫-查看
				tmbUnionpayPro.setProdCd("1161");
			}else if(i == 2){
				tmbUnionpayPro.setTransCd("1661"); //银联扫码反扫-查看
				tmbUnionpayPro.setProdCd("1661");
			}else if(i == 3){
				tmbUnionpayPro.setTransCd("1691"); //银联扫码反扫-开通
				tmbUnionpayPro.setProdCd("1691");
			}
			unionpayBizDealList.add(tmbUnionpayPro);
		}
		return unionpayBizDealList;
	}
	
	/**
	 * 获取临时表支付宝微信产品列表
	 * @param merinfo
	 * @param op
	 * @return
	 */
	public List<TblEditMchtBizDeal> getZwpayMchtBizDealList(TblEditMchtInf merinfo, Operators op){
		List<TblEditMchtBizDeal> zwpayBizDealList = new ArrayList<TblEditMchtBizDeal>();
		for(int i = 0; i < 4; i++){
			List<TblEditMchtBizDeal> tmbzwProAll = new ArrayList<TblEditMchtBizDeal>();
			if(i == 0){
				for(int m = 0; m < 2; m++){
					TblEditMchtBizDeal tmbzwPro = new TblEditMchtBizDeal();
					tmbzwPro.setMchtCd(merinfo.getId());
					tmbzwPro.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					tmbzwPro.setOperIn("I");
					tmbzwPro.setRecUpdOpr(String.valueOf(op.getId()));
					tmbzwPro.setRecCrtTs(new Date());
					if(m == 0){
						tmbzwPro.setProdCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
						tmbzwPro.setTransCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
					}else if(m == 1){
						tmbzwPro.setProdCd("1361");
						tmbzwPro.setTransCd("1361");
					}
					tmbzwProAll.add(tmbzwPro);
				}
				zwpayBizDealList.addAll(tmbzwProAll);
			}else if(i == 1){
				for(int m = 0; m < 2; m++){
					TblEditMchtBizDeal tmbzwPro = new TblEditMchtBizDeal();
					tmbzwPro.setMchtCd(merinfo.getId());
					tmbzwPro.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					tmbzwPro.setOperIn("I");
					tmbzwPro.setRecUpdOpr(String.valueOf(op.getId()));
					tmbzwPro.setRecCrtTs(new Date());
					if(m == 0){
						tmbzwPro.setProdCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
						tmbzwPro.setTransCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
					}else if(m == 1){
						tmbzwPro.setProdCd("1561");
						tmbzwPro.setTransCd("1561");
					}
					tmbzwProAll.add(tmbzwPro);
				}
				zwpayBizDealList.addAll(tmbzwProAll);
			}else if(i == 2){
				for(int m = 0; m < 2; m++){
					TblEditMchtBizDeal tmbzwPro = new TblEditMchtBizDeal();
					tmbzwPro.setMchtCd(merinfo.getId());
					tmbzwPro.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					tmbzwPro.setOperIn("I");
					tmbzwPro.setRecUpdOpr(String.valueOf(op.getId()));
					tmbzwPro.setRecCrtTs(new Date());
					if(m == 0){
						tmbzwPro.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
						tmbzwPro.setTransCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
					}else if(m == 1){
						tmbzwPro.setProdCd("1461");
						tmbzwPro.setTransCd("1461");
					}
					tmbzwProAll.add(tmbzwPro);
				}
				zwpayBizDealList.addAll(tmbzwProAll);
			}else if(i == 3){
				for(int m = 0; m < 2; m++){
					TblEditMchtBizDeal tmbzwPro = new TblEditMchtBizDeal();
					tmbzwPro.setMchtCd(merinfo.getId());
					tmbzwPro.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					tmbzwPro.setOperIn("I");
					tmbzwPro.setRecUpdOpr(String.valueOf(op.getId()));
					tmbzwPro.setRecCrtTs(new Date());
					if(m == 0){
						tmbzwPro.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
						tmbzwPro.setTransCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
					}else if(m == 1){
						tmbzwPro.setProdCd("1261");
						tmbzwPro.setTransCd("1261");
					}
					tmbzwProAll.add(tmbzwPro);
				}
				zwpayBizDealList.addAll(tmbzwProAll);
			}
		}
		return zwpayBizDealList;
	}
	
	/**
	 * 获取临时表银联扫码/支付宝微信费率列表
	 * @param tempFee
	 * @param merinfo
	 * @param op
	 * @param flagCode
	 * @return
	 * @throws ServiceException 
	 */
	public List<TblEditMchtBizFee> getUnionAndZwPayFeeList(TblEditMchtBizFee tmpFee, TblEditMchtInf merinfo, Operators op, String flagCode, boolean isCheckFee) throws ServiceException{
		List<TblEditMchtBizFee> mchtBizFees = new ArrayList<TblEditMchtBizFee>();
		if(flagCode != null && flagCode.length() > 0){
			if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(flagCode)){
				if(tmpFee != null){
					for(int m = 0;m < 2;m++){ //添加银联扫码-正扫、反扫
						TblEditMchtBizFee utempFee = new TblEditMchtBizFee();
						utempFee.setMchtCd(merinfo.getId());
						utempFee.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
						utempFee.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
						utempFee.setMchtAFeeMd("0");
						utempFee.setMchtAFeeSame("0");
						utempFee.setMchtFeeMd("0");
						utempFee.setMchtFeePercent(tmpFee.getMchtFeePercent());
						utempFee.setMchtFeePctMax(tmpFee.getMchtFeePctMax());
						utempFee.setOperIn("I");
						utempFee.setRecUpdOpr(String.valueOf(op.getId()));
						utempFee.setRecCrtTs(new Date());
						if(m == 0){
							utempFee.setProdCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION);
						}else if(m == 1){
							utempFee.setProdCd("1691");
						}
						mchtBizFees.add(utempFee);
					}
				}
			}else{
				for (int i = 0; i< 4; i++){
					TblEditMchtBizFee ztempFee = new TblEditMchtBizFee();
					ztempFee.setMchtCd(merinfo.getId());
					ztempFee.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					ztempFee.setSubBizCd(ConfigMerinfoUtil.YL_ZW_FUNCTION);
					ztempFee.setMchtAFeeMd("0");
					ztempFee.setMchtAFeeSame("0");
					ztempFee.setMchtFeeMd("0");
					if(isCheckFee){
						if(tmpFee.getMchtFeePercent()<0.3) throw new  ServiceException(MerinfoReturninfo.S_44.getName());
					}
					ztempFee.setMchtFeePercent(tmpFee.getMchtFeePercent());
					ztempFee.setMchtFeePctMax(tmpFee.getMchtFeePctMax());
					ztempFee.setOperIn("I");
					ztempFee.setRecUpdOpr(String.valueOf(op.getId()));
					ztempFee.setRecCrtTs(new Date());
					if(i == 0){
						ztempFee.setProdCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
					}else if (i == 1){
						ztempFee.setProdCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
					}else if(i == 2){
						ztempFee.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
					}else if(i == 3){
						ztempFee.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
					}
					mchtBizFees.add(ztempFee);
				}
			}
		}
		return mchtBizFees;
	}
	
	/**
	 * 获取正式表银联扫码/支付宝微信产品类型列表
	 * @param merinfoNo
	 * @param productList
	 * @param op
	 * @return
	 */
	public List<TblMchtBizDeal> getMchtBizDealList(String merinfoNo, List<String> productList, Operators op){
		List<TblMchtBizDeal> mchtBizDeals = new ArrayList<TblMchtBizDeal>();
		for(String tmbPro : productList){
			TblMchtBizDeal tmbProther=new TblMchtBizDeal();
			tmbProther.setMchtCd(merinfoNo);
			if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(tmbPro)){ //银联扫码正扫-开通
				tmbProther.setProdCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION);
				tmbProther.setTransCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION);
			}else if("1161".equals(tmbPro)){ //银联扫码正扫-查看
				tmbProther.setProdCd("1161");
				tmbProther.setTransCd("1161");
			}else if("1661".equals(tmbPro)){ //银联扫码反扫-查看
				tmbProther.setProdCd("1661");
				tmbProther.setTransCd("1661");
			}else if("1691".equals(tmbPro)){ //银联扫码反扫-开通
				tmbProther.setProdCd("1691");
				tmbProther.setTransCd("1691");
			}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(tmbPro)){
				tmbProther.setProdCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
				tmbProther.setTransCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
			}else if("1361".equals(tmbPro)){
				tmbProther.setProdCd("1361");
				tmbProther.setTransCd("1361");
			}else if(ConfigMerinfoUtil.ZPAY_FUNCTION_Z.equals(tmbPro)){
				tmbProther.setProdCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
				tmbProther.setTransCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
			}else if("1561".equals(tmbPro)){
				tmbProther.setProdCd("1561");
				tmbProther.setTransCd("1561");
			}else if(ConfigMerinfoUtil.WPAY_FUNCTION_Z.equals(tmbPro)){
				tmbProther.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
				tmbProther.setTransCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
			}else if("1461".equals(tmbPro)){
				tmbProther.setProdCd("1461");
				tmbProther.setTransCd("1461");
			}else if(ConfigMerinfoUtil.WPAY_FUNCTION_F.equals(tmbPro)){
				tmbProther.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
				tmbProther.setTransCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
			}else if("1261".equals(tmbPro)){
				tmbProther.setProdCd("1261");
				tmbProther.setTransCd("1261");
			}
			tmbProther.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
			tmbProther.setOperIn("I");
			tmbProther.setRecUpdOpr(String.valueOf(op.getId()));
			tmbProther.setRecCrtTs(new Date());
			mchtBizDeals.add(tmbProther);
		}
		return mchtBizDeals;
	}
	
	/**
	 * 获取正式表银联扫码/支付宝微信产品手续费列表
	 * @param tmpTeb
	 * @param merinfoNo
	 * @param op
	 * @param prodCd
	 * @return
	 */
	public List<TblMchtBizFee> getMchtBizFeeSList(TblEditMchtBizFee tmpTeb, String merinfoNo, Operators op, String prodCd){
		List<TblMchtBizFee> mchtBizFeeList = new ArrayList<TblMchtBizFee>();
		if(prodCd != null && prodCd.length() > 0){
			if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(prodCd)){
				if(tmpTeb != null){
					for(int m = 0; m < 2;m++){
						TblMchtBizFee uteb=new TblMchtBizFee();
						uteb.setMchtCd(merinfoNo);
						uteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
						uteb.setSubBizCd(tmpTeb.getSubBizCd());
						uteb.setMchtFeePercent(tmpTeb.getMchtFeePercent());
						uteb.setMchtFeePctMax(tmpTeb.getMchtFeePctMax());
						uteb.setMchtFeeMd("0"); ///未知参数不能为空
						uteb.setMchtAFeeSame("0"); ///未知参数不能为空
						uteb.setMchtAFeeMd("0"); ///未知参数不能为空
						uteb.setOperIn("I");
						uteb.setRecUpdOpr(String.valueOf(op.getId()));
						uteb.setRecCrtTs(new Date());
						if(m == 0){		//银联扫码正扫
							uteb.setProdCd(ConfigMerinfoUtil.UNIONPAY_FUNCTION);	
						}else if(m == 1){	//银联扫码反扫
							uteb.setProdCd("1691");
						}
						mchtBizFeeList.add(uteb);
					}
				}
			}else{
				for (int i = 0; i< 4; i++){
					TblMchtBizFee zteb=new TblMchtBizFee();
						zteb.setMchtCd(merinfoNo);
						zteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
						zteb.setSubBizCd(tmpTeb.getSubBizCd());
						zteb.setMchtFeePercent(tmpTeb.getMchtFeePercent());
						zteb.setMchtFeePctMax(tmpTeb.getMchtFeePctMax());
						zteb.setMchtFeeMd("0"); ///未知参数不能为空
						zteb.setMchtAFeeSame("0"); ///未知参数不能为空
						zteb.setMchtAFeeMd("0"); ///未知参数不能为空
						zteb.setOperIn("I");
						zteb.setRecUpdOpr(String.valueOf(op.getId()));
						zteb.setRecCrtTs(new Date());
						if(i == 0){
							zteb.setProdCd(ConfigMerinfoUtil.ZWPAY_FUNCTION);
						}else if (i == 1){
							zteb.setProdCd(ConfigMerinfoUtil.ZPAY_FUNCTION_Z);
						}else if(i == 2){
							zteb.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_Z);
						}else if(i == 3){
							zteb.setProdCd(ConfigMerinfoUtil.WPAY_FUNCTION_F);
						}
					mchtBizFeeList.add(zteb);
				}
			}
		}
		return mchtBizFeeList;
	}
	
	/**
	 * 获取临时表直连商户产品码列表
	 * @param dproMap
	 * @param productCode
	 * @param merinfo
	 * @param oprId
	 * @return
	 */
	public List<TblEditMchtBizDeal> getDirectEditMchtBizDealList(Map<String, String> dproMap, String productCode, String merinfo, String oprId){
		List<TblEditMchtBizDeal> editMchtBizDeals = new ArrayList<TblEditMchtBizDeal>();
		Iterator<?> iter=dproMap.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<?,?> entry = (Map.Entry<?,?>) iter.next();
			String key = (String) entry.getKey();
			TblEditMchtBizDeal dtmb=new TblEditMchtBizDeal();
			dtmb.setMchtCd(merinfo);
			if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(productCode)){
				dtmb.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T1);
				dtmb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
			}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(productCode)){
				dtmb.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T0);
				dtmb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
			}
			dtmb.setTransCd(key);
			dtmb.setOperIn("I");
			dtmb.setRecUpdOpr(String.valueOf(oprId));
			dtmb.setRecCrtTs(new Date());
			editMchtBizDeals.add(dtmb);
		}
		return editMchtBizDeals;
	}
	
	/**
	 * 获取临时表直连T1/T0商户产品手续费列表
	 * @return
	 * @throws ServiceException 
	 */
	public List<TblEditMchtBizFee> getEditMchtBizFeeList(String prodCd, List<TblEditMchtBizFee> feeList, String merinfoNo, String oprId, boolean isCheckFee) throws ServiceException{
		List<TblEditMchtBizFee> editMchtBizFees = new ArrayList<TblEditMchtBizFee>();
		if(prodCd != null && prodCd.length() > 0){
			if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(prodCd)){	//直连T1
				for(int k = 0; k < 4; k++){
					TblEditMchtBizFee dteb=null;
					if(k == 0){
						dteb = feeList.get(0);
						dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2);	//直连T1境内借记卡手续费
						if(isCheckFee){
							if(dteb.getMchtFeePercent()<0.5) throw new  ServiceException(MerinfoReturninfo.S_25.getName());
						}
					}else if(k == 1){
						dteb=feeList.get(1);
						dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1);	//直连T1境内贷记卡手续费
						if(isCheckFee){
							if(dteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_26.getName());
						}
					}else{
						dteb = new TblEditMchtBizFee();
						if(k == 2){
							dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);	//直连T1境内准贷记卡手续费
							TblEditMchtBizFee bizFeeModule = feeList.get(1);
							dteb.setMchtFeePercent(bizFeeModule.getMchtFeePercent());
							dteb.setMchtFeePctMax(bizFeeModule.getMchtFeePctMax());
						}else{
							dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4);	//直连T1通用手续费
							dteb.setMchtFeePercent(0.6d);
							dteb.setMchtFeePctMax(0d);
						}
					}
					dteb.setMchtCd(merinfoNo);//商户号
					dteb.setProdCd(prodCd);//产品  业务类型
					dteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					dteb.setMchtFeeMd("0"); ///未知参数不能为空
					dteb.setMchtAFeeSame("0"); ///未知参数不能为空
					dteb.setMchtAFeeMd("0"); ///未知参数不能为空
					dteb.setOperIn("I");
					dteb.setRecUpdOpr(oprId);
					dteb.setRecCrtTs(new Date());
					editMchtBizFees.add(dteb);
				}
			}else{		//直连T0
				for(int k = 0; k < 6; k++){
					TblEditMchtBizFee dtteb=null;
					if(k ==0){
						dtteb=feeList.get(2);	//直连T0借记卡手续费
						dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4);
						if(isCheckFee){
							if(dtteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_23.getName());
						}
					}else if(k == 1){
						dtteb=feeList.get(3);	//直连T0贷记卡手续费
						dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2);
						if(isCheckFee){
							if(dtteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_24.getName());
						}
					}else{
						dtteb = new TblEditMchtBizFee();
						if(k == 2){		//直连通用手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1);
							dtteb.setMchtFeePercent(0.6d);
							dtteb.setMchtFeePctMax(0d);
						}else if(k ==3){	//直连预付卡手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);
							dtteb.setMchtFeePercent(0.6d);
							dtteb.setMchtFeePctMax(0d);
						}else if(k == 4){	//产品手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_5);
							dtteb.setMchtFeePercent(0d);
							dtteb.setMchtFeePctMax(0d);
						}else{		//实时划付手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_6);
							dtteb.setMchtFeePercent(0d);
							dtteb.setMchtFeePctMax(0d);
						}
					}
					dtteb.setMchtCd(merinfoNo);//商户号
					dtteb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
					dtteb.setMchtFeeMd("0"); ///未知参数不能为空
					dtteb.setMchtAFeeSame("0"); ///未知参数不能为空
					dtteb.setMchtAFeeMd("0"); ///未知参数不能为空
					dtteb.setProdCd(prodCd);// 产品编号  T1/T0
					dtteb.setOperIn("I");
					dtteb.setRecUpdOpr(oprId);
					dtteb.setRecCrtTs(new Date());
					editMchtBizFees.add(dtteb);
				}
			}
		}
		return editMchtBizFees;
	} 
	
	/**
	 * 获取正式表直连T1/T0商户产品手续费列表
	 * @param prodCd
	 * @param feeList
	 * @param merinfoNo
	 * @param oprId
	 * @return
	 * @throws ServiceException
	 */
	public List<TblMchtBizFee> getMchtBizFeeDList(String prodCd, List<TblMchtBizFee> feeList, String merinfoNo, String oprId) throws ServiceException{
		List<TblMchtBizFee> mchtBizFees = new ArrayList<TblMchtBizFee>();
		if(prodCd != null && prodCd.length() > 0){
			if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(prodCd)){	//直连T1
				for(int k = 0; k < 4; k++){
					TblMchtBizFee dteb=null;
					if(k == 0){
						dteb = feeList.get(0);
						dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2);	//直连T1境内借记卡手续费
						if(dteb.getMchtFeePercent()<0.5) throw new  ServiceException(MerinfoReturninfo.S_25.getName());
					}else if(k == 1){
						dteb=feeList.get(1);
						dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1);	//直连T1境内贷记卡手续费
						if(dteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_26.getName());
					}else{
						dteb = new TblMchtBizFee();
						if(k == 2){
							dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);	//直连T1境内准贷记卡手续费
							TblMchtBizFee bizFeeModule = feeList.get(1);
							dteb.setMchtFeePercent(bizFeeModule.getMchtFeePercent());
							dteb.setMchtFeePctMax(bizFeeModule.getMchtFeePctMax());
						}else{
							dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4);	//直连T1通用手续费
							dteb.setMchtFeePercent(0.6d);
							dteb.setMchtFeePctMax(0d);
						}
					}
					dteb.setMchtCd(merinfoNo);//商户号
					dteb.setProdCd(prodCd);//产品  业务类型
					dteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
					dteb.setMchtFeeMd("0"); ///未知参数不能为空
					dteb.setMchtAFeeSame("0"); ///未知参数不能为空
					dteb.setMchtAFeeMd("0"); ///未知参数不能为空
					dteb.setOperIn("I");
					dteb.setRecUpdOpr(oprId);
					dteb.setRecCrtTs(new Date());
					mchtBizFees.add(dteb);
				}
			}else{		//直连T0
				for(int k = 0; k < 6; k++){
					TblMchtBizFee dtteb=null;
					if(k ==0){
						dtteb=feeList.get(2);	//直连T0借记卡手续费
						dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4);
						if(dtteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_23.getName());
					}else if(k == 1){
						dtteb=feeList.get(3);	//直连T0贷记卡手续费
						dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2);
						if(dtteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_24.getName());
					}else{
						dtteb = new TblMchtBizFee();
						if(k == 2){		//直连通用手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1);
							dtteb.setMchtFeePercent(0.6d);
							dtteb.setMchtFeePctMax(0d);
						}else if(k ==3){	//直连预付卡手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);
							dtteb.setMchtFeePercent(0.6d);
							dtteb.setMchtFeePctMax(0d);
						}else if(k == 4){	//产品手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_5);
							dtteb.setMchtFeePercent(0d);
							dtteb.setMchtFeePctMax(0d);
						}else{		//实时划付手续费
							dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_6);
							dtteb.setMchtFeePercent(0d);
							dtteb.setMchtFeePctMax(0d);
						}
					}
					dtteb.setMchtCd(merinfoNo);//商户号
					dtteb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
					dtteb.setMchtFeeMd("0"); ///未知参数不能为空
					dtteb.setMchtAFeeSame("0"); ///未知参数不能为空
					dtteb.setMchtAFeeMd("0"); ///未知参数不能为空
					dtteb.setProdCd(prodCd);// 产品编号  T1/T0
					dtteb.setOperIn("I");
					dtteb.setRecUpdOpr(oprId);
					dtteb.setRecCrtTs(new Date());
					mchtBizFees.add(dtteb);
				}
			}
		}
		return mchtBizFees;
	} 
	
	/**
	 * 获取临时表T1/T0产品码列表
	 * @param proMap
	 * @param merinfoNo
	 * @param productCode
	 * @param operId
	 * @return
	 */
	public List<TblEditMchtBizDeal> getEditMchtBizDealTList(Map<String, String> proMap, String merinfoNo, String productCode, String operId){
		List<TblEditMchtBizDeal> tblEditMchtBizDealList = new ArrayList<TblEditMchtBizDeal>();
		Iterator<?> iter=proMap.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<?,?> entry = (Map.Entry<?,?>) iter.next();
			String key = (String) entry.getKey();
			TblEditMchtBizDeal bizDealtmb=new TblEditMchtBizDeal();
			bizDealtmb.setMchtCd(merinfoNo);
			if(productCode.equals(ConfigMerinfoUtil.T1_FUNCTION)){//t1
				bizDealtmb.setProdCd(ConfigMerinfoUtil.T1_FUNCTION);
				bizDealtmb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD); 
			}else if(productCode.equals(ConfigMerinfoUtil.T0_FUNCTION)){//t0
				bizDealtmb.setProdCd(ConfigMerinfoUtil.T0_FUNCTION);
				bizDealtmb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
			}
			bizDealtmb.setTransCd(key);
			bizDealtmb.setOperIn("I");
			bizDealtmb.setRecUpdOpr(String.valueOf(operId));
			bizDealtmb.setRecCrtTs(new Date());
			tblEditMchtBizDealList.add(bizDealtmb);
		}
		return tblEditMchtBizDealList;
	}
	
	/**
	 * 获取临时表银行卡T1/T0产品手续费列表
	 * @param productCode
	 * @param feeList
	 * @param merinfoNo
	 * @param oprId
	 * @return
	 * @throws ServiceException
	 */
	public List<TblEditMchtBizFee> getTblEditMchtBizFeeT(String productCode, List<TblEditMchtBizFee> feeList, String merinfoNo, Operators op, boolean isCheckFee) throws ServiceException{
		List<TblEditMchtBizFee> editMchtBizFeeT = new ArrayList<TblEditMchtBizFee>();
		if(ConfigMerinfoUtil.T1_FUNCTION.equals(productCode)){		////银行卡T1
			 long subbizCd=1000;
			 for (int k=0;k<2;k++) {
				TblEditMchtBizFee tteb=null;
				if(k==0){//借记卡手续费
					tteb=feeList.get(0);
					tteb.setSubBizCd("000"+subbizCd);
					if(isCheckFee){
						if(tteb.getMchtFeePercent()<0.45) throw new  ServiceException(MerinfoReturninfo.S_25.getName());
						if(tteb.getMchtFeePctMax()<18 || tteb.getMchtFeePctMax() > 999) throw new  ServiceException(MerinfoReturninfo.S_52.getName());
					}
				}else{//贷记卡手续费
					tteb=feeList.get(1);
					tteb.setSubBizCd("000"+(subbizCd+1));
					if(isCheckFee){
						if(tteb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_26.getName());
					}
				}
				tteb.setMchtCd(merinfoNo);//商户号
				tteb.setProdCd(productCode);//产品  业务类型
				tteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
				tteb.setMchtFeeMd("0"); ///未知参数不能为空
				tteb.setMchtAFeeSame("0"); ///未知参数不能为空
				tteb.setMchtAFeeMd("0"); ///未知参数不能为空
				tteb.setOperIn("I");
				tteb.setRecUpdOpr(String.valueOf(op.getId()));
				tteb.setRecCrtTs(new Date());
				editMchtBizFeeT.add(tteb);
			}
		}else{		//银行卡T0
			long subbizCd=2000;
			for (int k=0;k<4;k++) {
				TblEditMchtBizFee tebb=null;
				if(k==0){//借记卡
					tebb=feeList.get(2);
					tebb.setSubBizCd("000"+subbizCd);
					if(isCheckFee){
						if(tebb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_23.getName());
						if(tebb.getMchtFeePctMax() > 0){ //如果设置了封顶值则限制范围
							if(tebb.getMchtFeePctMax() < 20 || tebb.getMchtFeePctMax() > 999) {
								throw new  ServiceException(MerinfoReturninfo.S_66.getName());
							}else{
								if(tebb.getMchtAFeePercent() < 0.03 || tebb.getMchtAFeePercent() > 0.99){
									throw new  ServiceException(MerinfoReturninfo.S_67.getName());
								}
							}
						}
					}
				}else if(k==1){
					tebb=feeList.get(3);
					tebb.setSubBizCd("000"+(subbizCd+1));
					if(isCheckFee){
						if(tebb.getMchtFeePercent()<0.55) throw new  ServiceException(MerinfoReturninfo.S_24.getName());
					}
				}else {
					tebb=new TblEditMchtBizFee();
					if(k==2){
						tebb.setSubBizCd("000"+(subbizCd+4));
					}else{
						tebb.setSubBizCd("000"+(subbizCd+5));
					}
					tebb.setMchtFeePercent(0d);
					tebb.setMchtFeePctMax(0d);
				}
				tebb.setMchtCd(merinfoNo);//商户号
				tebb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
				tebb.setMchtFeeMd("0"); ///未知参数不能为空
				tebb.setMchtAFeeSame("0"); ///未知参数不能为空
				tebb.setMchtAFeeMd("0"); ///未知参数不能为空
				tebb.setProdCd(productCode);// 产品编号  T1/T0
				tebb.setOperIn("I");
				tebb.setRecUpdOpr(String.valueOf(op.getId()));
				tebb.setRecCrtTs(new Date());
				editMchtBizFeeT.add(tebb);
			}
		}
		return editMchtBizFeeT;
	}
	
	/**
	 * 商户审核详情手续费显示处理
	 * @param objList_fee
	 * @param merinfo
	 * @param showName
	 * @return
	 */
	public List<TblEditMchtBizFee> getMerinfoEditMchtBizFeeList(List<?> objList_fee, TblEditMchtInf merinfo, Boolean showName){
		List<TblEditMchtBizFee> merEditMchtBizFeeList = new ArrayList<TblEditMchtBizFee>();
		if(null!=objList_fee && objList_fee.size()>0){
			Iterator<?> iter=objList_fee.iterator();
			while(iter.hasNext()){
				Object[] obj=(Object[])iter.next();
				if((ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(obj[3]))){
				TblEditMchtBizFee dfee=new TblEditMchtBizFee();
					dfee.setMchtCd(String.valueOf(obj[0]));
					dfee.setProdCd(String.valueOf(obj[1]));
					dfee.setBizCd(String.valueOf(obj[2]));
					dfee.setSubBizCd(String.valueOf(obj[3]));
					if(null != obj[4] || !(obj[4].toString().trim().equals(""))){
						dfee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
					}
				if(null == obj[5] || obj[5].toString().trim().equals("")){ 
					dfee.setMchtFeePctMax(0d);
				}else{
					dfee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
				}
				if(showName){
					String name="";
					if(ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(dfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4.equals(dfee.getSubBizCd())){
						name="直连T0借记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(dfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(dfee.getSubBizCd())){
						name="直连T0贷记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(dfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1.equals(dfee.getSubBizCd())){
						name="直连T1境内贷记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(dfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(dfee.getSubBizCd())){
						name="直连T1境内借记卡手续费";
					}
					dfee.setMchtFeeMd(name);
				}
					merEditMchtBizFeeList.add(dfee); 
				}
			}
				
		}
		return merEditMchtBizFeeList;
	}
	
	/**
	 * 获取正式产品表产品列表信息
	 * @param productStr
	 * @param newMerinfo
	 * @param merinfoNo
	 * @param operId
	 * @return
	 * @throws ServiceException 
	 */
	
	public List<TblMchtBizDeal> getTblMchtBizDealA(String[] productStr, String groupCd, String merinfoNo, String operId, String zmchtinfNo) throws ServiceException{
		List<TblMchtBizDeal> tblMchtBizDealList = new ArrayList<TblMchtBizDeal>();
		String[] productCodeFlag=queryMchtBizDealArray(zmchtinfNo, false, false);
		if(null!=productStr && productStr.length>0 ){
			if(Constant.STR_NUMBER_ONE.equals(groupCd) && (Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
					Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){
				for (int i = 0; i < productStr.length; i++) {
					TblMchtBizDeal tmbd=new TblMchtBizDeal();
					tmbd.setMchtCd(merinfoNo);
					if(productStr[i].equals(ConfigMerinfoUtil.DIRECT_FUNCTION_T0)){// 直连t0
						tmbd.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T0);
						tmbd.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
					}else{//t1
						tmbd.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T1);	//直连t1
						tmbd.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD); 
					}
					tmbd.setTransCd(productStr[i]);
					tmbd.setOperIn("I");
					tmbd.setRecUpdOpr(String.valueOf(operId));
					tmbd.setRecCrtTs(new Date());
					tblMchtBizDealList.add(tmbd);
					}
				}else{
					for (int i = 0; i < productStr.length; i++) {
						TblMchtBizDeal tmb=new TblMchtBizDeal();
						tmb.setMchtCd(merinfoNo);
						if(productStr[i].equals(ConfigMerinfoUtil.T0_FUNCTION)){// 银行卡t0
							tmb.setProdCd(ConfigMerinfoUtil.T0_FUNCTION);
							tmb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
						}else{//t1
							tmb.setProdCd(ConfigMerinfoUtil.T1_FUNCTION);	//银行卡t1
							tmb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD); 
						}
						tmb.setTransCd(productStr[i]);
						tmb.setOperIn("I");
						tmb.setRecUpdOpr(String.valueOf(operId));
						tmb.setRecCrtTs(new Date());
						tblMchtBizDealList.add(tmb);
					}
				}
		}
		return tblMchtBizDealList;
	}
	
	/**
	 * 获取直连商户T0-除贷记卡、借记卡外的产品手续费
	 * @param merinfoNo
	 * @param operId
	 * @return
	 */
	public List<TblMchtBizFee> getTblMchtBizFeeDT0(String merinfoNo, String operId){
		List<TblMchtBizFee> mchtBizFeeDT0List = new ArrayList<TblMchtBizFee>();
		for(int m = 0;m < 4; m++){
			TblMchtBizFee dtteb = new TblMchtBizFee();
			 if(m == 0){		//直连通用手续费
				dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1);
				dtteb.setMchtFeePercent(0.6d);
				dtteb.setMchtFeePctMax(0d);
			 }else if(m == 1){		//直连预付卡手续费
				dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);
				dtteb.setMchtFeePercent(0.6d);
				dtteb.setMchtFeePctMax(0d);
			 }else if(m == 2){		//产品手续费
				dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_5);
				dtteb.setMchtFeePercent(0d);
				dtteb.setMchtFeePctMax(0d);
			 }else{		//实时划付手续费
				dtteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_6);
				dtteb.setMchtFeePercent(0d);
				dtteb.setMchtFeePctMax(0d);
			}
			dtteb.setMchtCd(merinfoNo);//商户号
			dtteb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
			dtteb.setMchtFeeMd("0"); ///未知参数不能为空
			dtteb.setMchtAFeeSame("0"); ///未知参数不能为空
			dtteb.setMchtAFeeMd("0"); ///未知参数不能为空
			dtteb.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T0);// 产品编号  T1/T0
			dtteb.setOperIn("I");
			dtteb.setRecUpdOpr(operId);
			dtteb.setRecCrtTs(new Date());
			mchtBizFeeDT0List.add(dtteb);
		}
		return mchtBizFeeDT0List;
	}
	
	/**
	 * 获取直连商户T1-除贷记卡、借记卡外的产品手续费
	 * @param merinfoNo
	 * @param operId
	 * @return
	 */
	public List<TblMchtBizFee> getTblMchtBizFeeDT1(String merinfoNo, String operId){
		List<TblMchtBizFee> mchtBizFeeDT1List = new ArrayList<TblMchtBizFee>();
		for(int m = 0;m < 2; m++){
			TblMchtBizFee dteb = new TblMchtBizFee();
			 if(m == 0){
				dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_3);  //直连T1境内准贷记卡手续费
				dteb.setMchtFeePercent(mchtFeeDtPercent);
				dteb.setMchtFeePctMax(mchtFeeDtPctMax);
			}else{
				dteb.setSubBizCd(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4);  //直连T1通用手续费
				dteb.setMchtFeePercent(0.6d);
				dteb.setMchtFeePctMax(0d);
			}
			dteb.setMchtCd(merinfoNo);//商户号
			dteb.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T1);//产品  业务类型
			dteb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
			dteb.setMchtFeeMd("0"); ///未知参数不能为空
			dteb.setMchtAFeeSame("0"); ///未知参数不能为空
			dteb.setMchtAFeeMd("0"); ///未知参数不能为空
			dteb.setOperIn("I");
			dteb.setRecUpdOpr(operId);
			dteb.setRecCrtTs(new Date());
			mchtBizFeeDT1List.add(dteb);
		}
		return mchtBizFeeDT1List;
	}
	
	/**
	 * 获取银行卡T0产品添加服务费、划付费
	 * @param merinfoNo
	 * @param operId
	 * @return
	 */
	public List<TblMchtBizFee> getTblMchtBizFeeYT1(String merinfoNo, String operId){
		List<TblMchtBizFee> mchtBizFeeYT0List = new ArrayList<TblMchtBizFee>();
		for (int i = 0; i < 2; i++) {//添加服务费，划付费
			TblMchtBizFee  teb=new TblMchtBizFee();
			teb.setMchtCd(merinfoNo);//商户号
			teb.setProdCd(ConfigMerinfoUtil.T0_FUNCTION);//产品  业务类型
			if(i==0){
				teb.setSubBizCd(ConfigMerinfoUtil.T0_2004_FUNCTION);
			}else{
				teb.setSubBizCd(ConfigMerinfoUtil.T0_2005_FUNCTION);
			}
			teb.setMchtFeePercent(0d);
			teb.setMchtFeePctMax(0d);
			teb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
			teb.setMchtFeeMd("0"); ///未知参数不能为空
			teb.setMchtAFeeSame("0"); ///未知参数不能为空
			teb.setMchtAFeeMd("0"); ///未知参数不能为空
			teb.setOperIn("I");
			teb.setRecUpdOpr(String.valueOf(operId));
			teb.setRecCrtTs(new Date());
			mchtBizFeeYT0List.add(teb);
		}
		return mchtBizFeeYT0List;
	}

	/**
	 * 获取正式表银行卡T1/T0手续费
	 * @param MerinfoNo
	 * @param tmpTeb
	 * @param operId
	 * @return
	 */
	public TblMchtBizFee getTblMchtBizFeeTT(String merinfoNo, TblEditMchtBizFee tmpTeb, String operId){
		TblMchtBizFee teb = new TblMchtBizFee();
		String subBizCdStr=tmpTeb.getSubBizCd().substring(3, 4);
			if(subBizCdStr.equals("1")){//t1
				teb.setProdCd(ConfigMerinfoUtil.T1_FUNCTION);//产品  业务类型
				teb.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
			}else if(subBizCdStr.equals("2")){//t0
				teb.setProdCd(ConfigMerinfoUtil.T0_FUNCTION);//产品  业务类型
				teb.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
				if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(tmpTeb.getSubBizCd())){
					if(tmpTeb.getMchtAFeePercent() != null){
						teb.setMchtAFeePercent(tmpTeb.getMchtAFeePercent());
					}
				}
			}
			teb.setMchtCd(merinfoNo);
			teb.setSubBizCd(tmpTeb.getSubBizCd());
			teb.setMchtFeePercent(tmpTeb.getMchtFeePercent());
			teb.setMchtFeePctMax(tmpTeb.getMchtFeePctMax());
			teb.setMchtFeeMd("0"); ///未知参数不能为空
			teb.setMchtAFeeSame("0"); ///未知参数不能为空
			teb.setMchtAFeeMd("0"); ///未知参数不能为空
			teb.setOperIn("I");
			teb.setRecUpdOpr(operId);
			teb.setRecCrtTs(new Date());
		return teb;
	}
	
	/**
	 * 获取正式表直连商户T1/T0手续费
	 * @param tmpTeb
	 * @param prodCd
	 * @param merinfoNo
	 * @param operId
	 * @return
	 */
	public TblMchtBizFee getMchtBizFeeDtt(TblEditMchtBizFee tmpTeb, String prodCd,String merinfoNo, String operId){
		TblMchtBizFee mchtBizFeeDtt = new TblMchtBizFee();
		if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(prodCd)){	//直连T1境内贷记卡手续费/直连T1境内借记卡手续费
			if(ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1.equals(tmpTeb.getSubBizCd())){
				mchtFeeDtPercent = tmpTeb.getMchtFeePercent();
				mchtFeeDtPctMax = tmpTeb.getMchtFeePctMax();
			}
			mchtBizFeeDtt.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T1);	//产品  业务类型
			mchtBizFeeDtt.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
		}else{
			mchtBizFeeDtt.setProdCd(ConfigMerinfoUtil.DIRECT_FUNCTION_T0);	//直连借记卡手续费/直连贷记卡手续费
			mchtBizFeeDtt.setBizCd(ConfigMerinfoUtil.T0_BIZ_CD);
		}
			mchtBizFeeDtt.setMchtCd(merinfoNo);
			mchtBizFeeDtt.setSubBizCd(tmpTeb.getSubBizCd());
			mchtBizFeeDtt.setMchtFeePercent(tmpTeb.getMchtFeePercent());
			mchtBizFeeDtt.setMchtFeePctMax(tmpTeb.getMchtFeePctMax());
			mchtBizFeeDtt.setMchtFeeMd("0"); ///未知参数不能为空
			mchtBizFeeDtt.setMchtAFeeSame("0"); ///未知参数不能为空
			mchtBizFeeDtt.setMchtAFeeMd("0"); ///未知参数不能为空
			mchtBizFeeDtt.setOperIn("I");
			mchtBizFeeDtt.setRecUpdOpr(operId);
			mchtBizFeeDtt.setRecCrtTs(new Date());
			return mchtBizFeeDtt;
	}
	
	/**
	 * 商户查看详情手续费显示处理
	 * @param objList_fee
	 * @param merinfo
	 * @param showName
	 * @return
	 */
	public List<TblMchtBizFee> getMerinfoMchtBizFeeList(List<?> objList_fee, TblMchtInf merinfo, Boolean showName){
		List<TblMchtBizFee> merMchtBizFeeList = new ArrayList<TblMchtBizFee>();
		if(null!=objList_fee && objList_fee.size()>0){
			Iterator<?> iter=objList_fee.iterator();
			while(iter.hasNext()){
				Object[] obj=(Object[])iter.next();
				if((ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4.equals(obj[3]))
					|| (ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(obj[1]) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(obj[3]))){
				TblMchtBizFee dtfee=new TblMchtBizFee();
				dtfee.setMchtCd(String.valueOf(obj[0]));
				dtfee.setProdCd(String.valueOf(obj[1]));
				dtfee.setBizCd(String.valueOf(obj[2]));
				dtfee.setSubBizCd(String.valueOf(obj[3]));
				if(null != obj[4] || !(obj[4].toString().trim().equals(""))){
					dtfee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
				}
				if(null == obj[5] || obj[5].toString().trim().equals("")){ 
					dtfee.setMchtFeePctMax(0d);
				}else{
					dtfee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
				}
				if(showName){
					String name="";
					if(ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(dtfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_4.equals(dtfee.getSubBizCd())){
						name="直连T0借记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T0.equals(dtfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(dtfee.getSubBizCd())){
						name="直连T0贷记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(dtfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_1.equals(dtfee.getSubBizCd())){
						name="直连T1境内贷记卡手续费";
					}else if(ConfigMerinfoUtil.DIRECT_FUNCTION_T1.equals(dtfee.getProdCd()) && ConfigMerinfoUtil.DIRECT_SUBIZ_CD_2.equals(dtfee.getSubBizCd())){
						name="直连T1境内借记卡手续费";
					}
						dtfee.setMchtFeeMd(name);
					}
					merMchtBizFeeList.add(dtfee);
				}
			}
		}
		return merMchtBizFeeList;
	}
	
	/**
	 * 加载装机区域
	 * @param areaCode
	 * @param flag
	 * @return
	 */
	public TblDictionaryLayerItem loadInstalledArea(String areaCode, String flag){
		TblDictionaryLayerItem  dictionaryLayerItem = null;
		Object[] params=new Object[2];
		String sql = "select t.dic_code,t.dic_pcode,t.name from tbl_dictionarylayeritem t where t.dic_type = 'UnionPay_Area' and t.dic_level = ? and t.dic_code = ? ";
		params[0]=flag;
		params[1]=areaCode;
		try {
			Object object=sqlBaseDao.findObj(sql, params);
			if(object != null){
				Object[] obj = (Object[])object;
				dictionaryLayerItem = new TblDictionaryLayerItem();
				dictionaryLayerItem.getId().setDicCode(String.valueOf(obj[0]));
				dictionaryLayerItem.getId().setDicPcode(String.valueOf(obj[1]));
				dictionaryLayerItem.setName(String.valueOf(obj[2]));
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(),e);
		}
		return dictionaryLayerItem;
	}
	
	/**
	 * 获取装机地址城市
	 * @param ucBccdCode
	 * @return
	 */
	public String getInstalledCity(String ucBccdCode){
		String areaCityCode = "";
		TblDictionaryLayerItem dictionaryCity = null;
		if(ucBccdCode != null && ucBccdCode.length() > 0){
			String areaCode = ucBccdCode.substring(4, ucBccdCode.length());
				dictionaryCity = loadInstalledArea(areaCode, "2");
			if(dictionaryCity == null){
				dictionaryCity = loadInstalledArea(areaCode, "3");	//直辖市
			}
			if(dictionaryCity != null){
				areaCityCode = dictionaryCity.getId().getDicCode();
			}
		}
		return areaCityCode;
	}
	
	/**
	 * 获取装机地址省份
	 * @param ucBccdCode
	 * @return
	 */
	public String getInstalledProvince(String ucBccdCode){
		String areaProvinceCode = "";
		TblDictionaryLayerItem dictionaryCity = null;
		if(ucBccdCode != null &&ucBccdCode.length() > 0){
			String areaCodep = ucBccdCode.substring(4, ucBccdCode.length());
				dictionaryCity = loadInstalledArea(areaCodep, "2");
			if(dictionaryCity == null){
				dictionaryCity = loadInstalledArea(areaCodep, "3");	//直辖市
			}
			if(dictionaryCity != null){
				TblDictionaryLayerItem dictionaryProvince = loadInstalledArea(dictionaryCity.getId().getDicPcode(), "1");
				if(dictionaryProvince != null){
					areaProvinceCode = dictionaryProvince.getId().getDicCode();
				}
			}
		}
		return areaProvinceCode;
	}
	
	
	public Double getMchtFeeDtPercent() {
		return mchtFeeDtPercent;
	}

	public void setMchtFeeDtPercent(Double mchtFeeDtPercent) {
		this.mchtFeeDtPercent = mchtFeeDtPercent;
	}

	public Double getMchtFeeDtPctMax() {
		return mchtFeeDtPctMax;
	}

	public void setMchtFeeDtPctMax(Double mchtFeeDtPctMax) {
		this.mchtFeeDtPctMax = mchtFeeDtPctMax;
	}

	@Override
	public TblEditMchtInf getTblEditMchtInfByMerId(String merId) throws ServiceException {
		Object[] params = {merId};
		TblEditMchtInf editMchtInf = null;
		String hql = " from TblEditMchtInf t where t.id=? ";
		try {
			editMchtInf = (TblEditMchtInf)baseDao.createQueryUniqueResult(hql, params);
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询临时商户信息失败！");
		}
		return editMchtInf;
	}

	@Override
	public Long getTReceiveCountInfByMerId(String merId) throws ServiceException {
		Long rcount = 0l;
		String sql = " SELECT COUNT(1) FROM T_RECEIVE T WHERE T.MERNO="+merId+" AND T.STATUS = '0' ";
		try {
			Object obj = baseDao.createSQLQueryUniqueResult(sql);
			rcount = Long.parseLong(obj.toString());
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询临时商户被领件次数失败！");
		}
		return rcount;
	}

	/**
	 * 获取暂存商户信息
	 * @param merchantInfo
	 * @param op
	 * @return
	 * @throws ServiceException
	 */
	public TblEditMchtInf mergMerInfoToSave(TblEditMchtInf merchantInfo, Operators op) throws ServiceException {
		TblEditMchtInf merInfoSave = merchantInfo;
		try {
			String ucBcCd = merInfoSave.getUcBccd();
			if(ucBcCd.length() > 0){
				merInfoSave.setUcBccd(op.getOrgCode().substring(0, 4)+ucBcCd);	//32域
			}
			if(merInfoSave.getUpMccCd().length() > 0){
				merInfoSave.setMcc(merInfoSave.getUpMccCd());
			}
			String nameBusi = merInfoSave.getNameBusi();
			if(nameBusi.length() > 0){
				merInfoSave.setNameBusi(nameBusi.trim());	//商户简称
			}
			merInfoSave.setApplDate(DateUtil.getDate(new Date(), 0, "yyyy-MM-dd"));
			merInfoSave.setSn("0000");
			String sql="SELECT T.INS_COMPANY_CD FROM TBL_INS_INF T WHERE T.INS_ID_CD=? AND INS_TYPE=1";
			Object[] params={op.getOrgCode()};
			Object parentOrg=sqlBaseDao.findObj(sql, params);
			merInfoSave.setAipBranCd(String.valueOf(parentOrg));	//所属分公司
			if("2".equals(merInfoSave.getGroupCD()) && (Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
					|| Role.OPERATORS_LEAD.getCode().equals(op.getRoleType()))){ ////所属机构
				merInfoSave.setBankBelongCd(merInfoSave.getBankBelongCd());
			}else{
				merInfoSave.setBankBelongCd(op.getOrgCode()); 
			}
			merInfoSave.setOriChnl("0");	//商户来源渠道 0主动发展
			String nationCd = merInfoSave.getNationCd();
			if(nationCd.length() > 0){
				merInfoSave.setNationCd(nationCd.trim());	//商户注册地址默---- 已用作商户类型  对公或对私
			}
			merInfoSave.setRecUpdOpr(String.valueOf(op.getId()));	//进件人id
			merInfoSave.setOperIn("I");
			merInfoSave.setStatus(MerinfoStatus.S_9.getCode());		//暂存状态
			merInfoSave.setRecCrtTs(new Date());	//新增时间
			String groupCd = merInfoSave.getGroupCD();
			if(groupCd == null || groupCd.trim().length() < 1){
				merInfoSave.setGroupCD(op.getGroupCd());	//商户直连间连选择  默认为间连
			}else{
				merInfoSave.setGroupCD(groupCd);	//商户直连间连选择
			}
			if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){ //业务员取上级id
				merInfoSave.setExt1(String.valueOf(op.getSuperiorId()));
			}else if(Role.OPERATORS_COMM.getCode().equals(op.getRoleType())){ //运营专员
				if("2".equals(merInfoSave.getGroupCD())){
					merInfoSave.setExt1(merInfoSave.getExt1()); //直营商户可动态选择所属代理商
				}else{
					merInfoSave.setExt1(String.valueOf(op.getSuperiorId())); //非直营取上级id
				}
			}else if("2".equals(merInfoSave.getGroupCD()) && Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){ //受理市场运营
				merInfoSave.setExt1(merInfoSave.getExt1()); //直营商户可动态选择所属代理商
			}else{
				merInfoSave.setExt1(String.valueOf(op.getId())); //其他情况保存当前登录人自己
			}
			if("2".equals(merInfoSave.getGroupCD()) && Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())){ ////机构号
				String ext1 = merInfoSave.getExt1();
				if(ext1 != null && ext1.length() > 0){
					Operators opr = powerInfoService.loadOperatorsById(Long.valueOf(ext1)); 
					if(opr != null){
						merInfoSave.setUcBccdArea(opr.getOneagentid());
					}
				}
			}else{
				merInfoSave.setUcBccdArea(op.getOneagentid());	
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询登录人所属分公司失败！");
		}
		return merInfoSave;
	}
	
	public List<TblEditMchtPicture> mergPictrueListToSave(TblEditMchtInf merchantInfo, Operators op, boolean flag){
		List<TblEditMchtPicture> mchtPictureToSave = new ArrayList<TblEditMchtPicture>();
		List<TblEditMchtPicture> pictrueList = merchantInfo.getPictrueList();
		if(pictrueList != null){
			for(TblEditMchtPicture pi : pictrueList){
				if(!(pi.getUrl()==null || pi.getUrl().equals("") || pi.getUrl().length()<1)){
					TblEditMchtPicture pictrue=new TblEditMchtPicture();
					pictrue.setMchtCd(merchantInfo.getId());
					pictrue.setUrl(pi.getUrl().trim());	//图片地址
					pictrue.setPindex(1);	//顺序默认
					Random ra=new Random();
					int random=1000+ra.nextInt(8999);
					int first=pi.getUrl().trim().indexOf("mid=")+4;
					int sencond=pi.getUrl().trim().lastIndexOf("&");
					if(first>4 && sencond>0){
						pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
						pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
						pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
					}else{
						String b=pi.getUrl().trim().substring(pi.getUrl().lastIndexOf("&")+1);
						pictrue.setPcode("code");//拆封名称去掉后缀
						pictrue.setFileName(b);//名称
						pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
					}
					pictrue.setDocType("00");
					pictrue.setSystemflag("00");
					if(flag){
						pictrue.setStatus("0");
					}else{
						pictrue.setStatus("09");
					}
					pictrue.setRecOprId("I");//插入操作
					pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
					pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
					mchtPictureToSave.add(pictrue);
				}
			}
		}
		return mchtPictureToSave;
	}
	
	@Override
	public Map getOpIdsTreeBySuperId( Operators op) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getSLOpIdsTreeBySuperId(op);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询受理市场人员ID和名字信息出错！");
		}
		return map;
	}
	/**
	 * 查询直营商户驳回记录
	 * @param merNo
	 * @return
	 * @throws ServiceException 
	 */
	public TblEditMchtExtendInfo getMerExtendInfo(String merNo) throws ServiceException{
		TblEditMchtExtendInfo emchtExtendInfos = null;
		try {
			String esql = "from TblEditMchtExtendInfo t where t.id=? and t.backup2='1'";
			Object[] params = {merNo};
			emchtExtendInfos=(TblEditMchtExtendInfo)pageDao.createQueryUniqueResult(esql, params);
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询直营商户驳回信息出错！");
		}
		return emchtExtendInfos;
	}
	/**
	 * 审核查询商户信息
	 * @param merinfoNo 临时商户号
	 * @param showName 是否根据code显示名称
	 * @return TblEditMchtInf  商户信息
	 * @author zbl    v1.0
	 * @author pc  后期改造可细化每个查询语句需要的字段、改用SQL 查询
	 * */
	 
	@Transactional(readOnly=true)
	public TblEditMchtInf queryPreMerinfoTmpInfo(String mer_infoNo,boolean showName,boolean isOpName) throws ServiceException {
		 TblEditMchtInf mer_info=null;
		
		 Object[] param={mer_infoNo};
		 try {
			if(null==mer_infoNo) return mer_info; //为空返回
			
			//商户信息
			String mer_hql=" from TblEditMchtInf t where t.id=?";
			mer_info=(TblEditMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
			if(showName){//根据code显示名称
				mer_info.setCertifType(ConfigMerinfoUtil.getCertifType(mer_info.getCertifType()));//证件类型
				if(null==mer_info.getProvCd() || mer_info.getProvCd().trim().length()<5)mer_info.setProvCd("310000");
				if(null==mer_info.getCityCd() || mer_info.getCityCd().trim().length()<5)mer_info.setCityCd("310100");
				if(null==mer_info.getAreaCd() || mer_info.getAreaCd().trim().length()<5)mer_info.setAreaCd("310104");
				mer_info.setProvCd(ConfigMerinfoUtil.getGBProviceName(mer_info.getProvCd()));//省份
				mer_info.setCityCd(ConfigMerinfoUtil.getGBCityName(mer_info.getCityCd()));//城市
				mer_info.setAreaCd(ConfigMerinfoUtil.getGBAreaName(mer_info.getAreaCd()));//地区
				
			}
			if(isOpName){
				//查询进件人员(后期可放入与商户联查，提高页面响应速度)
				String q_sql="SELECT T.REAL_NAME FROM T_OPERATORS T WHERE T.ID=?";
				Object[] params_1={mer_info.getRecUpdOpr()};
				Object op_name=pageDao.findObj(q_sql, params_1);
				mer_info.setRecUpdOpr(String.valueOf(op_name));
			}
			//终端信息
			String ter_hql="from TblEditTermInf t where t.id.MchtCd=?";
			List<?> objList_ter=pageDao.queryAll(ter_hql, param);
			if(null!=objList_ter && objList_ter.size()>0){
				List<TblEditTermInf> terList=new ArrayList<TblEditTermInf>();
				for (Object object : objList_ter) {
					TblEditTermInf terminfo=(TblEditTermInf)object;
					if(showName){
						terminfo.setTermTp(ConfigMerinfoUtil.getPosType(terminfo.getTermTp()));//获取终端类型具体名称
					}
					//查询终端风控信息
					String risk_hql="from TblEditTermRiskCfg t where t.id.MchtCd=? and t.id.TermId=?";
					 Object[] param_risk={mer_infoNo,terminfo.getId().getTermId()};
					List<?> objList_risk=pageDao.queryAll(risk_hql, param_risk);
					if(null!=objList_risk && objList_risk.size()>0){
						List<TblEditTermRiskCfg> riskList=new ArrayList<TblEditTermRiskCfg>();
						for (Object risk : objList_risk) {
							TblEditTermRiskCfg fee=(TblEditTermRiskCfg)risk;
							riskList.add(fee);
						}
						terminfo.setRiskCfgList(riskList); //set 终端风控信息
					}
					terList.add(terminfo);
				}
				mer_info.setTerminfoList(terList);//set终端
				TblEditTermRiskCfg  tmpTb= new TblEditTermRiskCfg();
				tmpTb.setAccpetStartTime(terList.get(0).getRiskCfgList().get(0).getAccpetStartTime());
				tmpTb.setAccpetEndTime(terList.get(0).getRiskCfgList().get(0).getAccpetEndTime());
				mer_info.setTerminfoRisk(tmpTb);//获取营业时间
			}
			//产品信息
			String del_hql="select t.prodCd,t.transCd from  TblEditMchtBizDeal t where t.mchtCd=?";
			List<?> objList_del=pageDao.queryAll(del_hql, param);
			if(null!=objList_del && objList_del.size()>0){
				List<TblEditMchtBizDeal> delList=new ArrayList<TblEditMchtBizDeal>();
				String[] produdctArrayStr=new String[objList_del.size()];
				int i=0;
				Iterator<?> iter=objList_del.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblEditMchtBizDeal terminfo=new TblEditMchtBizDeal();
					terminfo.setProdCd(String.valueOf(obj[0]));
					terminfo.setTransCd(String.valueOf(obj[1]));
					delList.add(terminfo);
						produdctArrayStr[i]=terminfo.getTransCd();
					i++;
				}
				 
				mer_info.setBizDelList(delList); //产品集合
				mer_info.setProductStrs(produdctArrayStr);//产品
				
				String[] productCodeStr=queryMchtBizDealArray(mer_infoNo, false,showName);
				mer_info.setProductCode(productCodeStr); //保存当前商户所选择的业务模式 
			}
			
			
			//结算信息
			String settle_hql="from TblEditMchtBankAccount t where t.ownerCd=?";
			TblEditMchtBankAccount bankAccount=(TblEditMchtBankAccount)baseDao.createQueryUniqueResult(settle_hql,param );
			mer_info.setBankAccount(bankAccount);//SET 结算信息
			
			//手续费
			String fees_hql = "";
			String[] productCodeFlag=queryMchtBizDealArray(mer_infoNo, false, false);
			
			fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax,mchtAFeePercent from TblEditMchtBizFee t where t.mchtCd=? ";
			
			List<?> objList_fee=pageDao.queryAll(fees_hql, param);
			
			if(null!=objList_fee && objList_fee.size()>0){
				List<TblEditMchtBizFee> feeList=new ArrayList<TblEditMchtBizFee>();
				Iterator<?> iter=objList_fee.iterator();
				int i=0;
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					if(!(ConfigMerinfoUtil.ZPAY_FUNCTION_Z.equals(obj[1]) || ConfigMerinfoUtil.WPAY_FUNCTION_Z.equals(obj[1]) 
							|| ConfigMerinfoUtil.WPAY_FUNCTION_F.equals(obj[1]) || "1691".equals(obj[1]))){
						if(obj[3].equals(ConfigMerinfoUtil.T0_2005_FUNCTION) || 
								   obj[3].equals(ConfigMerinfoUtil.T0_2004_FUNCTION)){//t0 划付手续费  跳过
									continue;
							}
								if(String.valueOf(obj[3]).equals("0002000") && i==0){//只有t0
									feeList.add(null);
									feeList.add(null);
								}
								TblEditMchtBizFee fee=new TblEditMchtBizFee();
								fee.setMchtCd(String.valueOf(obj[0]));
								fee.setProdCd(String.valueOf(obj[1]));
								fee.setBizCd(String.valueOf(obj[2]));
								fee.setSubBizCd(String.valueOf(obj[3]));
								fee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
								if(null == obj[5] || obj[5].toString().trim().equals("")){ 
									fee.setMchtFeePctMax(0d);
								}else{
									fee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
								}
								if(showName){
									String name="";
									if(fee.getProdCd().equals(ConfigMerinfoUtil.T1_FUNCTION)){
										name="T1";
									}else if(fee.getProdCd().equals(ConfigMerinfoUtil.T0_FUNCTION)){
										name="T0";
									}else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(fee.getProdCd())){
										name = "银联";
									}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(fee.getProdCd())){
										name = "支付宝微信";
									}
									String feeCodeName = ConfigMerinfoUtil.getFeeList(String.valueOf(obj[3])); //根据code 显示手续费名称
									fee.setMchtFeeMd(name + (feeCodeName == null ? "" : feeCodeName));
								}
								//D0代付服务费费率
								if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(String.valueOf(obj[3])) && 
										null != obj[6] && !obj[6].toString().trim().equals("")){
									fee.setMchtAFeePercent(Double.parseDouble(String.valueOf((obj[6]))));
								}
								feeList.add(fee); 
								i++;
					}
				}
				mer_info.setFee(feeList); //set手续费集合
			}
			
			//图片信息
			String pic_hql="select t.Url,t.DocType  from TblEditMchtPicture t where t.MchtCd=? order by t.Pcode ASC ";
			List<?> objList_pic=pageDao.queryAll(pic_hql, param);
			if(null!=objList_pic && objList_pic.size()>0){
				List<TblEditMchtPicture> picList=new LinkedList<TblEditMchtPicture>();
				Iterator<?> iter=objList_pic.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					TblEditMchtPicture picture=new TblEditMchtPicture();
					String url=String.valueOf(obj[0]);
					//url=url.substring(url.lastIndexOf("/")+1);
					picture.setUrl(url);
					picList.add(picture); 
				}
				mer_info.setPictrueList(picList);//图片路径地址
			}
		   //扩展信息
			String extend_hql="from TblEditMchtExtendInfo t where t.id=?";
			TblEditMchtExtendInfo tblEditMchtExtendInfo = (TblEditMchtExtendInfo)baseDao.createQueryUniqueResult(extend_hql,param );
			if(tblEditMchtExtendInfo!=null){
				if(StringUtils.isNotEmpty(tblEditMchtExtendInfo.getDevelopPerson())){
					String operator_hql="from Operators t where t.id=?";
					Object[] paramR={Long.parseLong(tblEditMchtExtendInfo.getDevelopPerson())};
					Operators operators = (Operators)baseDao.createQueryUniqueResult(operator_hql,paramR);
					if(operators != null){
						tblEditMchtExtendInfo.setDevelopPersonName(operators.getRealName());
					}
				}
			}
			mer_info.setMchtExtendInfo(tblEditMchtExtendInfo);
			return  mer_info;
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException(e.getMessage(),e);
		}
	}
	
	/**
	 * 预审核直营商户信息
	 * @param op 操作员
	 * @return TblEditMchtInf  商户信息
	 * @author jjj   
	 * @throws  
	 * */
	@Transactional(rollbackFor = { ServiceException.class })
	public synchronized String preCheckMerinfo(Operators op, TblEditMchtInf newMerinfo) throws ServiceException {
		try {
			if(null == newMerinfo || null==newMerinfo.getId() || newMerinfo.getId().trim().length()!=15) return MerinfoReturninfo.S_10.getName();
			if(null==newMerinfo.getUcBccd() || newMerinfo.getUcBccd().length()<5 || newMerinfo.getUcBccd().substring(4).equals("null")) return MerinfoReturninfo.S_17.getName();
			if(null==newMerinfo.getUpMccCd()) return MerinfoReturninfo.S_28.getName();
			String checkFlag=newMerinfo.getMchtExtendInfo().getBackup2();
			//审核通过
			if(checkFlag.equals("01")){
				//更新商户扩展临时表数据
				String p_sql="UPDATE tbl_edit_mcht_extend_info e SET e.backup4=to_char(sysdate,'yyyy-MM-dd HH24:mi:ss'),e.backup2='0',e.backup1=?,e.backup3=? WHERE e.mcth_cd=?";
				List<Object> exmerList=new ArrayList<Object>();
				exmerList.add(op.getAccountNo());
				exmerList.add(newMerinfo.getMchtExtendInfo().getBackup3());
				exmerList.add(newMerinfo.getId());
				int p_count=sqlBaseDao.deleteBySql(p_sql, exmerList);
				if(p_count<1){ 
					logger.info("----直营审核通过更新商户["+newMerinfo.getId()+"]扩展临时表信息失败-----");
					throw new ServiceException(MerinfoReturninfo.S_54.getName());
				}
				logger.info("------直营审核更通过新商户["+newMerinfo.getId()+"]扩展临时表信息成功----"); 
				//更新商户临时表状态为00
				String r_sql="UPDATE tbl_edit_mcht_inf T SET T.STATUS='00'  WHERE T.STATUS='14' AND  T.mcht_cd=?";
				List<Object> merList=new ArrayList<Object>();
				merList.add(newMerinfo.getId());
				int r_count=sqlBaseDao.deleteBySql(r_sql, merList);
				if(r_count<1){ 
					logger.info("----直营审核通过更新商户["+newMerinfo.getId()+"]临时表状态失败-----");
					throw new ServiceException(MerinfoReturninfo.S_54.getName());
				}
				logger.info("------直营审核通过更新商户["+newMerinfo.getId()+"]状态成功----"); 
				return MerinfoReturninfo.S_53.getName()+"_"+newMerinfo.getId();
				
			}else{//驳回
				//更新商户扩展临时表数据
				String p_sql="UPDATE tbl_edit_mcht_extend_info e SET e.backup4=to_char(sysdate,'yyyy-MM-dd HH24:mi:ss'),e.backup2='1',e.backup1=?,e.backup3=? WHERE e.mcth_cd=?";
				List<Object> exmerList=new ArrayList<Object>();
				exmerList.add(op.getAccountNo());
				exmerList.add(newMerinfo.getMchtExtendInfo().getBackup3());
				exmerList.add(newMerinfo.getId());
				int p_count=sqlBaseDao.deleteBySql(p_sql, exmerList);
				if(p_count<1){ 
					logger.info("----直营审核驳回更新商户["+newMerinfo.getId()+"]扩展临时表信息失败-----");
					throw new ServiceException(MerinfoReturninfo.S_56.getName());
				}
				logger.info("------直营审核驳回更新商户["+newMerinfo.getId()+"]扩展临时表信息成功----"); 
				//更新商户临时表状态为00
				String r_sql="UPDATE tbl_edit_mcht_inf T SET T.STATUS='15'  WHERE T.STATUS='14' AND  T.mcht_cd=?";
				List<Object> merList=new ArrayList<Object>();
				merList.add(newMerinfo.getId());
				int r_count=sqlBaseDao.deleteBySql(r_sql, merList);
				if(r_count<1){ 
					logger.info("----直营审核驳回更新商户["+newMerinfo.getId()+"]临时表状态失败-----");
					throw new ServiceException(MerinfoReturninfo.S_56.getName());
				}
				logger.info("------直营审核驳回更新商户["+newMerinfo.getId()+"]状态成功----"); 
				return MerinfoReturninfo.S_55.getName()+"_"+newMerinfo.getId();
			}
		} catch (DaoException e) {
			 logger.error(e.getMessage(),e);
			 throw new ServiceException("审核商户信息失败",e);
		}
	

	}
	
	/**
	 * 调用接口验证身份证合法性
	 * @param cardName
	 * @param cardNo
	 * @return
	 * @throws ServiceException 
	 */
	public boolean validateIdInfo(String cardName, String cardNo, String verifyFlag) throws ServiceException{
		boolean valResult = true;
		if(cardName.length()==0 || cardNo.length()==0){
			valResult = false;
			logger.info("============调用验证证件合法性接口：证件姓名或证件号为空============");
		}else{
			String verifyType = "type";
			String verifyTypeVal = "idCard";
			String verifyName = "name";
			String verifyNo = "citizenIdNumber";
			if("3".equals(verifyFlag)){
				verifyTypeVal = "two";
				verifyNo = "card";
			}
			//测试
			String url = Utils.getConfigValue("CREDIT_CK");
			JSONObject json = new JSONObject();
			json.put(verifyType, verifyTypeVal);
			json.put(verifyName, cardName);
			json.put(verifyNo, cardNo);
			try {
				logger.info("============调用验证身份证合法性接口开始============");
				String	result = HttpUtil.sendGetOrPostR(url, json.toString());
				logger.info("============调用验证证件合法性接口结束============");
				JSONObject resp = JSONObject.parseObject(result);
				String msgCode = resp.getString("msg_code");
				if(!"00".equals(msgCode)){
					return false;
				}
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				throw new ServiceException("调用验证身份证合法性接口失败！",e);
			}
		}
		return valResult;
	}
	
	/**
	 * 云商宝商户进件
	 */
	public void busiServePoInsertMerinfo(Long receiveId) throws ServiceException{
		try {
			////商户表
			TblMchtInf mchtInf = new TblMchtInf();
			String mid_8 = new SimpleDateFormat("ddHHmmss").format(new Date());
			Random ra = new Random();
			int mid_4 = 1000 + ra.nextInt(9001);
			String mchtNo = "950"+ mid_8 + Integer.toString(mid_4);
			mchtInf.setId(mchtNo);
			mchtInf.setAipBranCd("85270000");
			mchtInf.setGroupCD("3");
			mchtInf.setBankBelongCd("48502000");
			String applDate = DateUtil.getDate(new Date(), 0, "yyyy-MM-dd");
			mchtInf.setApplDate(applDate);
			String merName = "";
			Operators operators = null;
			OperatorReceive operatorReceive = (OperatorReceive)baseDao.loadById(receiveId, OperatorReceive.class);
			if(operatorReceive != null){
				OperatorAuth operatorAuth = (OperatorAuth)baseDao.loadById(operatorReceive.getOperatorAuthId(), OperatorAuth.class);
				if(operatorAuth != null){
					operators = findMerchantByNo(operatorAuth.getAccountNo());
					if(operators != null){
						merName = operators.getRealName();
						mchtInf.setCertifType(operators.getCardType());
						mchtInf.setCertifNo(operators.getCardNo());
						mchtInf.setRegAddr(operators.getAddress());
						mchtInf.setContactPhoneNo(operators.getMobile());
					}
				}
			}
			mchtInf.setName("个体户-"+merName);
			mchtInf.setNameBusi(mchtInf.getName());
			mchtInf.setCertif(merName);
			mchtInf.setApprDate(new Date());
			mchtInf.setStatus("01");
			mchtInf.setUcBccd("00000000");
			mchtInf.setRecCrtTs(new Date());
			mchtInf.setOperIn("I");
			baseDao.editSave(mchtInf);
			logger.info("-----云商宝商户进件保存商户信息成功--商户号："+mchtInf.getId());
			////终端表
			for(int i = 1; i <= 2; i++){
				TblTermInfId tb_id=new TblTermInfId();
				String terId="0000000"+i;
				tb_id.setMchtCd(mchtInf.getId());//商户号
				tb_id.setTermId(terId); //终端号码
				TblTermInf termInf = new TblTermInf();
				termInf.setId(tb_id);
				termInf.setTermTp("3"); //1固定 3移动
				termInf.setTmnlMoneyIntype("1"); //0按照商户  1按照终端
				termInf.setDealTypes("1"); //是否需要强扣 0否 1是
				termInf.setActiveCode("0"); //资金冻结生效状态 0未生效 1生效
				termInf.setDialOut("60000");//终端呼出号码
				termInf.setStatus("01");//初始状态
				termInf.setDeviceCd("YJ");//默认sn号码
				termInf.setRecCrtTs(new Date());//记录时间
				baseDao.editSave(termInf);
				logger.info("-----云商宝商户进件保存第"+i+"个终端信息成功--商户号："+mchtInf.getId()+"--终端号："+termInf.getId());
			}
			////产品表
			for(int i = 0; i < 4; i++){
				TblMchtBizDeal bizDeal=new TblMchtBizDeal();
				bizDeal.setMchtCd(mchtInf.getId());
				bizDeal.setProdCd("1000");
				bizDeal.setBizCd("0000000");
				if(i == 1){
					bizDeal.setTransCd("1011");
				}else if(i == 2){
					bizDeal.setTransCd("1001");
				}else if(i == 3){
					bizDeal.setTransCd("2011");
				}else{
					bizDeal.setTransCd("4011");
				}
				bizDeal.setOperIn("I");
				bizDeal.setRecCrtTs(new Date());
				baseDao.editSave(bizDeal);
				logger.info("-----云商宝商户进件保存T1产品信息成功--商户号:"+mchtInf.getId()+"--prodCd:"+bizDeal.getProdCd()+"--transCd:"+bizDeal.getProdCd());
			}
			////产品费率
			long subbizCd=1000;
			for(int i = 0; i < 2; i++){
				TblMchtBizFee bizFee = new TblMchtBizFee();
				if(i == 0){ //T1借记卡手续费
					bizFee.setSubBizCd("000"+subbizCd);
					bizFee.setMchtFeePercent(0.6);
					bizFee.setMchtFeePctMax(25.0);
				}else{ //T1贷记卡手续费
					bizFee.setSubBizCd("000"+(subbizCd+1));
					bizFee.setMchtFeePercent(0.6);
					bizFee.setMchtFeePctMax(0.0);
				}
				bizFee.setMchtCd(mchtInf.getId());
				bizFee.setProdCd("1000");
				bizFee.setBizCd(ConfigMerinfoUtil.T1_BIZ_CD);
				bizFee.setMchtFeeMd("0"); ///未知参数不能为空
				bizFee.setMchtAFeeSame("0"); ///未知参数不能为空
				bizFee.setOperIn("I");
				baseDao.editSave(bizFee);
				logger.info("-----云商宝商户进件保存T1产品费率信息成功--商户号："+mchtInf.getId()+"--prodCd:"+bizFee.getProdCd()+"--subBizCd:"+bizFee.getSubBizCd());
			}
			////结算账户
			TblMchtBankAccount bankAccount = new TblMchtBankAccount();
			bankAccount.setOwnerCd(mchtInf.getId());
			bankAccount.setAccountType("01");
			String bname = operators == null ? "0" : operators.getBankAcctName(); //账户名称
			bankAccount.setName(bname);
			String bno = operators == null ? "0" : operators.getBankAcctNo(); //卡号
			bankAccount.setAccount(bno);
			String bankCode = operators == null ? "0" : operators.getBank_no(); //联行号
			bankAccount.setBankCode(bankCode);
			String bankName = operators == null ? "0" : operators.getBankDeposit();  //银行名称
			bankAccount.setBankName(bankName);
			String ucbccd = bankCode == "0" ? "0" : bankCode.substring(0, 3);
			bankAccount.setUcBccd(ucbccd);
			bankAccount.setOperIn("I");
			bankAccount.setRecCrtTs(new Date());
			baseDao.editSave(bankAccount);
			logger.info("-----云商宝商户进件保存结算账户信息成功--商户号："+mchtInf.getId());
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException(MerinfoReturninfo.S_57.getName());
		}
	}

	@Override
	public List<TblMchtBizFee> queryYsbMchtBizFeeList(String mchtNo) throws ServiceException {
		Object[] param={mchtNo};
		List<TblMchtBizFee> feeList=new ArrayList<TblMchtBizFee>();
		String querySql = "select t.MCHT_CD mchtCd,t.PROD_CD prodCd,t.BIZ_CD bizCd,t.SUB_BIZ_CD subBizCd,t.MCHT_FEE_PERCENT mchtFeePercent,"
		        +"t.MCHT_FEE_PCT_MAX mchtFeePctMax,a.mcht_fee_percent_new mchtFeePercentNew,a.mcht_fee_pct_max_new mchtFeePctMaxNew "
		        +"from TBL_MCHT_BIZ_FEE T left join tbl_mcht_biz_fee_his a on t.mcht_cd = a.mcht_cd and t.prod_cd = a.prod_cd "
		        +"and t.biz_cd = a.biz_cd and t.sub_biz_cd = a.sub_biz_cd and a.is_new_flag = 'Y' "
		        +"and to_char(a.rec_crt_ts, 'YYYYMMDD') = to_char(sysdate,'YYYYMMDD')"
		        +"where t.mcht_cd = ? order by t.prod_cd,t.sub_biz_cd ";
		try {
			List<?> objFeeList = pageDao.querySqlAll(querySql, param);
			if(objFeeList != null && objFeeList.size() > 0){
				Iterator<?> iter=objFeeList.iterator();
				while(iter.hasNext()){
					Object[] obj=(Object[])iter.next();
					if(obj[3].equals(ConfigMerinfoUtil.T1_1000_FUNCTION) || obj[3].equals(ConfigMerinfoUtil.T1_1001_FUNCTION)
							|| obj[3].equals(ConfigMerinfoUtil.T0_2000_FUNCTION) || obj[3].equals(ConfigMerinfoUtil.T0_2001_FUNCTION)){//只允许变更T1、T0手续费
						TblMchtBizFee mchtFee=new TblMchtBizFee();
						mchtFee.setMchtCd(String.valueOf(obj[0]));
						mchtFee.setProdCd(String.valueOf(obj[1]));
						mchtFee.setBizCd(String.valueOf(obj[2]));
						mchtFee.setSubBizCd(String.valueOf(obj[3]));
						if(null == obj[6] || obj[6].toString().trim().equals("")){
							mchtFee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
						}else{
							mchtFee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[6]))));
						}
						if(null == obj[7] || obj[7].toString().trim().equals("")){
							mchtFee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
						}else{
							mchtFee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[7]))));
						}
						String prodName = spliceProdName(mchtFee);
						mchtFee.setMchtFeeMd(prodName);	
						feeList.add(mchtFee);
					}
				}
			}
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new ServiceException(MerinfoReturninfo.S_58.getName());
		}
		return feeList;
	}
	
	//产品费率名称
	public String spliceProdName(TblMchtBizFee mchtFee){
		String prodName = "";
		if(ConfigMerinfoUtil.T1_FUNCTION.equals(mchtFee.getProdCd())){
			if(ConfigMerinfoUtil.T1_1000_FUNCTION.equals(mchtFee.getSubBizCd())){
				prodName = "T1境内借记卡手续费";
			}else if(ConfigMerinfoUtil.T1_1001_FUNCTION.equals(mchtFee.getSubBizCd())){
				prodName = "T1境内贷记卡手续费";
			}else{
				prodName = "未知手续费";
			}
		}
		if(ConfigMerinfoUtil.T0_FUNCTION.equals(mchtFee.getProdCd())){
			if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(mchtFee.getSubBizCd())){
				prodName = "T0境内借记卡手续费";
			}else if(ConfigMerinfoUtil.T0_2001_FUNCTION.equals(mchtFee.getSubBizCd())){
				prodName = "T0境内贷记卡手续费";
			}else{
				prodName = "未知手续费";
			}
		}
		return prodName;
	}

	@Override
	public String editYsbMchtFeeInfo(List<TblMchtBizFee> mchtBizFees, Operators op, TblMchtInf mchtInf) throws ServiceException {
		try {
			if(mchtBizFees != null && mchtBizFees.size() > 0){
				String upds_sql = "UPDATE TBL_MCHT_BIZ_FEE_HIS T SET T.IS_NEW_FLAG = 'N',T.REC_UPD_OPR=?,REC_CRT_TS=SYSDATE WHERE T.MCHT_CD=? ";
				List<Object> paramList=new ArrayList<Object>();
				paramList.add(op.getAccountNo());
				paramList.add(mchtInf.getId());
				sqlBaseDao.deleteBySql(upds_sql, paramList);
				logger.info("===============商户["+mchtInf.getId()+"]临时费率信息表更新成功！============="); 
				for(TblMchtBizFee mchtBizFee : mchtBizFees){
					if(ConfigMerinfoUtil.T1_1000_FUNCTION.equals(mchtBizFee.getSubBizCd())){ //T1借记卡手续费
						if(mchtBizFee.getMchtFeePercent() < 0.5 || mchtBizFee.getMchtFeePercent() > 0.75){
							return MerinfoReturninfo.S_61.getName();
						}
						if(mchtBizFee.getMchtFeePctMax() < 20 || mchtBizFee.getMchtFeePctMax() > 300){ //T1借记卡手续费封顶
							return MerinfoReturninfo.S_62.getName();
						}
					}
					if(ConfigMerinfoUtil.T1_1001_FUNCTION.equals(mchtBizFee.getSubBizCd())){ //T1贷记卡手续费
						if(mchtBizFee.getMchtFeePercent() < 0.55 || mchtBizFee.getMchtFeePercent() > 0.75){
							return MerinfoReturninfo.S_63.getName();
						}
					}
					if(ConfigMerinfoUtil.T0_2000_FUNCTION.equals(mchtBizFee.getSubBizCd())){ //T0借记卡手续费
						if(mchtBizFee.getMchtFeePercent() < 0.55 || mchtBizFee.getMchtFeePercent() > 0.75){
							return MerinfoReturninfo.S_64.getName();
						}
					}
					if(ConfigMerinfoUtil.T0_2001_FUNCTION.equals(mchtBizFee.getSubBizCd())){ //T0贷记卡手续费
						if(mchtBizFee.getMchtFeePercent() < 0.55 || mchtBizFee.getMchtFeePercent() > 0.75){
							return MerinfoReturninfo.S_65.getName();
						}
					}
					TblMchtBizFeeHis bizFeeHis = new TblMchtBizFeeHis();
					bizFeeHis.setMchtCd(mchtBizFee.getMchtCd());
					bizFeeHis.setProdCd(mchtBizFee.getProdCd());
					bizFeeHis.setBizCd(mchtBizFee.getBizCd());
					bizFeeHis.setSubBizCd(mchtBizFee.getSubBizCd());
					Object[] param={mchtBizFee.getMchtCd(),mchtBizFee.getProdCd(),mchtBizFee.getSubBizCd()};
					String queryOriFee_sql = "from TblMchtBizFee t where t.mchtCd=? and t.prodCd=? and t.subBizCd=? ";
					TblMchtBizFee oribizFee = (TblMchtBizFee)baseDao.createQueryUniqueResult(queryOriFee_sql, param);
					if(oribizFee != null){
						bizFeeHis.setMchtFeePercentOld(oribizFee.getMchtFeePercent());
						bizFeeHis.setMchtFeePctMaxOld(oribizFee.getMchtFeePctMax());
					}
					bizFeeHis.setMchtFeePercentNew(mchtBizFee.getMchtFeePercent());
					if(ConfigMerinfoUtil.T1_1000_FUNCTION.equals(bizFeeHis.getSubBizCd())){
						bizFeeHis.setMchtFeePctMaxNew(mchtBizFee.getMchtFeePctMax());
					}else{
						bizFeeHis.setMchtFeePctMaxNew(0.0); //T1贷记卡 T0借记卡 T0贷记卡无封顶值
					}
					bizFeeHis.setRecUpdOpr(String.valueOf(op.getAccountNo()));
					bizFeeHis.setRecCrtTs(new Date());
					bizFeeHis.setIsNewFlag("Y");
					baseDao.editSave(bizFeeHis);
					logger.info("===============添加云商宝商户临时费率表成功！商户号："+bizFeeHis.getMchtCd()+"==============");
					}
					logger.info("===============添加云商宝商户临时费率表完成！商户号："+mchtInf.getId()+"==============");
					//添加短信信息
					String merPhoneNo = mchtInf.getContactPhoneNo();
					if(merPhoneNo != null && merPhoneNo.length() > 0){
						MessageSend ms = new MessageSend();
						String smsContent="尊敬的商户，您的终端费率已调整。次日登陆APP商户信息可查看费率详情，如有疑问请咨询服务商。付临门云商宝客服4006078866";
						ms.setPhoneNumber(merPhoneNo);
						ms.setMesContent(smsContent);
						ms.setSendFlag("0");
						ms.setDtCreate(new Date());
						ms.setTimes(0);
						baseDao.editSave(ms);
						logger.info("保存发送短信内容："+smsContent);
					}else{
						logger.info("获取手机号失败，未发送短信！");
					}
				}
				return MerinfoReturninfo.S_60.getName();
			} catch (DaoException e) {
				logger.debug(e.getMessage(), e);
				throw new ServiceException("添加云商宝商户费率临时表失败");
			}
	}
	

}